1 /* Yacc grammar for bash. */
3 /* Copyright (C) 1989-2004 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"
45 #define NEED_STRFTIME_DECL /* used in externs.h */
51 #include "mailcheck.h"
53 #include "builtins/common.h"
54 #include "builtins/builtext.h"
58 #if defined (READLINE)
59 # include "bashline.h"
60 # include <readline/readline.h>
64 # include "bashhist.h"
65 # include <readline/history.h>
68 #if defined (JOB_CONTROL)
70 #endif /* JOB_CONTROL */
75 typedef void *alias_t;
78 #if defined (PROMPT_STRING_DECODE)
80 # include <sys/param.h>
83 # if defined (TM_IN_SYS_TIME)
84 # include <sys/types.h>
85 # include <sys/time.h>
86 # endif /* TM_IN_SYS_TIME */
88 #endif /* PROMPT_STRING_DECODE */
90 #define RE_READ_TOKEN -99
91 #define NO_EXPANSION -100
99 #if defined (HANDLE_MULTIBYTE)
100 # define last_shell_getc_is_singlebyte \
101 ((shell_input_line_index > 1) \
102 ? shell_input_line_property[shell_input_line_index - 1] \
104 # define MBTEST(x) ((x) && last_shell_getc_is_singlebyte)
106 # define last_shell_getc_is_singlebyte 1
107 # define MBTEST(x) ((x))
110 #if defined (EXTENDED_GLOB)
111 extern int extended_glob;
114 extern int eof_encountered;
115 extern int no_line_editing, running_under_emacs;
116 extern int current_command_number;
117 extern int sourcelevel;
118 extern int posixly_correct;
119 extern int last_command_exit_value;
120 extern int interrupt_immediately;
121 extern char *shell_name, *current_host_name;
122 extern char *dist_version;
123 extern int patch_level;
124 extern int dump_translatable_strings, dump_po_strings;
125 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
126 #if defined (BUFFERED_INPUT)
127 extern int bash_input_fd_changed;
131 /* **************************************************************** */
133 /* "Forward" declarations */
135 /* **************************************************************** */
138 static void debug_parser __P((int));
141 static int yy_getc __P((void));
142 static int yy_ungetc __P((int));
144 #if defined (READLINE)
145 static int yy_readline_get __P((void));
146 static int yy_readline_unget __P((int));
149 static int yy_string_get __P((void));
150 static int yy_string_unget __P((int));
151 static int yy_stream_get __P((void));
152 static int yy_stream_unget __P((int));
154 static int shell_getc __P((int));
155 static void shell_ungetc __P((int));
156 static void discard_until __P((int));
158 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
159 static void push_string __P((char *, int, alias_t *));
160 static void pop_string __P((void));
161 static void free_string_list __P((void));
164 static char *read_a_line __P((int));
166 static int reserved_word_acceptable __P((int));
167 static int yylex __P((void));
168 static int alias_expand_token __P((char *));
169 static int time_command_acceptable __P((void));
170 static int special_case_tokens __P((char *));
171 static int read_token __P((int));
172 static char *parse_matched_pair __P((int, int, int, int *, int));
173 #if defined (ARRAY_VARS)
174 static char *parse_compound_assignment __P((int *));
176 #if defined (DPAREN_ARITHMETIC) || defined (ARITH_FOR_COMMAND)
177 static int parse_dparen __P((int));
178 static int parse_arith_cmd __P((char **, int));
180 #if defined (COND_COMMAND)
181 static void cond_error __P((void));
182 static COND_COM *cond_expr __P((void));
183 static COND_COM *cond_or __P((void));
184 static COND_COM *cond_and __P((void));
185 static COND_COM *cond_term __P((void));
186 static int cond_skip_newlines __P((void));
187 static COMMAND *parse_cond_command __P((void));
189 #if defined (ARRAY_VARS)
190 static int token_is_assignment __P((char *, int));
191 static int token_is_ident __P((char *, int));
193 static int read_token_word __P((int));
194 static void discard_parser_constructs __P((int));
196 static char *error_token_from_token __P((int));
197 static char *error_token_from_text __P((void));
198 static void print_offending_line __P((void));
199 static void report_syntax_error __P((char *));
201 static void handle_eof_input_unit __P((void));
202 static void prompt_again __P((void));
204 static void reset_readline_prompt __P((void));
206 static void print_prompt __P((void));
208 #if defined (HISTORY)
209 char *history_delimiting_chars __P((void));
212 #if defined (HANDLE_MULTIBYTE)
213 static void set_line_mbstate __P((void));
214 static char *shell_input_line_property = NULL;
216 # define set_line_mbstate()
219 extern int yyerror __P((const char *));
225 /* Default prompt strings */
226 char *primary_prompt = PPROMPT;
227 char *secondary_prompt = SPROMPT;
229 /* PROMPT_STRING_POINTER points to one of these, never to an actual string. */
230 char *ps1_prompt, *ps2_prompt;
232 /* Handle on the current prompt string. Indirectly points through
233 ps1_ or ps2_prompt. */
234 char **prompt_string_pointer = (char **)NULL;
235 char *current_prompt_string;
237 /* Non-zero means we expand aliases in commands. */
238 int expand_aliases = 0;
240 /* If non-zero, the decoded prompt string undergoes parameter and
241 variable substitution, command substitution, arithmetic substitution,
242 string expansion, process substitution, and quote removal in
243 decode_prompt_string. */
246 /* If non-zero, $'...' and $"..." are expanded when they appear within
247 a ${...} expansion, even when the expansion appears within double
249 int extended_quote = 1;
251 /* The decoded prompt string. Used if READLINE is not defined or if
252 editing is turned off. Analogous to current_readline_prompt. */
253 static char *current_decoded_prompt;
255 /* The number of lines read from input while creating the current command. */
256 int current_command_line_count;
258 /* Variables to manage the task of reading here documents, because we need to
259 defer the reading until after a complete command has been collected. */
260 static REDIRECT *redir_stack[10];
263 /* Where shell input comes from. History expansion is performed on each
264 line when the shell is interactive. */
265 static char *shell_input_line = (char *)NULL;
266 static int shell_input_line_index;
267 static int shell_input_line_size; /* Amount allocated for shell_input_line. */
268 static int shell_input_line_len; /* strlen (shell_input_line) */
270 /* Either zero or EOF. */
271 static int shell_input_line_terminator;
273 /* The line number in a script on which a function definition starts. */
274 static int function_dstart;
276 /* The line number in a script on which a function body starts. */
277 static int function_bstart;
279 /* The line number in a script at which an arithmetic for command starts. */
280 static int arith_for_lineno;
282 /* The line number in a script where the word in a `case WORD', `select WORD'
283 or `for WORD' begins. This is a nested command maximum, since the array
284 index is decremented after a case, select, or for command is parsed. */
285 #define MAX_CASE_NEST 128
286 static int word_lineno[MAX_CASE_NEST];
287 static int word_top = -1;
289 /* If non-zero, it is the token that we want read_token to return
290 regardless of what text is (or isn't) present to be read. This
291 is reset by read_token. If token_to_read == WORD or
292 ASSIGNMENT_WORD, yylval.word should be set to word_desc_to_read. */
293 static int token_to_read;
294 static WORD_DESC *word_desc_to_read;
296 static REDIRECTEE redir;
300 WORD_DESC *word; /* the word that we read. */
301 int number; /* the number that we read. */
302 WORD_LIST *word_list;
306 PATTERN_LIST *pattern;
309 /* Reserved words. Members of the first group are only recognized
310 in the case that they are preceded by a list_terminator. Members
311 of the second group are for [[...]] commands. Members of the
312 third group are recognized only under special circumstances. */
313 %token IF THEN ELSE ELIF FI CASE ESAC FOR SELECT WHILE UNTIL DO DONE FUNCTION
314 %token COND_START COND_END COND_ERROR
315 %token IN BANG TIME TIMEOPT
317 /* More general tokens. yylex () knows how to make these. */
318 %token <word> WORD ASSIGNMENT_WORD
319 %token <number> NUMBER
320 %token <word_list> ARITH_CMD ARITH_FOR_EXPRS
321 %token <command> COND_CMD
322 %token AND_AND OR_OR GREATER_GREATER LESS_LESS LESS_AND LESS_LESS_LESS
323 %token GREATER_AND SEMI_SEMI LESS_LESS_MINUS AND_GREATER LESS_GREATER
326 /* The types that the various syntactical units return. */
328 %type <command> inputunit command pipeline pipeline_command
329 %type <command> list list0 list1 compound_list simple_list simple_list1
330 %type <command> simple_command shell_command
331 %type <command> for_command select_command case_command group_command
332 %type <command> arith_command
333 %type <command> cond_command
334 %type <command> arith_for_command
335 %type <command> function_def function_body if_command elif_clause subshell
336 %type <redirect> redirection redirection_list
337 %type <element> simple_command_element
338 %type <word_list> word_list pattern
339 %type <pattern> pattern_list case_clause_sequence case_clause
340 %type <number> timespec
341 %type <number> list_terminator
345 %left '&' ';' '\n' yacc_EOF
350 inputunit: simple_list simple_list_terminator
352 /* Case of regular command. Discard the error
353 safety net,and return the command just parsed. */
356 /* discard_parser_constructs (0); */
361 /* Case of regular command, but not a very
362 interesting one. Return a NULL command. */
363 global_command = (COMMAND *)NULL;
368 /* Error during parsing. Return NULL command. */
369 global_command = (COMMAND *)NULL;
371 /* discard_parser_constructs (1); */
383 /* Case of EOF seen by itself. Do ignoreeof or
385 global_command = (COMMAND *)NULL;
386 handle_eof_input_unit ();
392 { $$ = make_word_list ($1, (WORD_LIST *)NULL); }
394 { $$ = make_word_list ($2, $1); }
397 redirection: '>' WORD
400 $$ = make_redirection (1, r_output_direction, redir);
405 $$ = make_redirection (0, r_input_direction, redir);
410 $$ = make_redirection ($1, r_output_direction, redir);
415 $$ = make_redirection ($1, r_input_direction, redir);
417 | GREATER_GREATER WORD
420 $$ = make_redirection (1, r_appending_to, redir);
422 | NUMBER GREATER_GREATER WORD
425 $$ = make_redirection ($1, r_appending_to, redir);
430 $$ = make_redirection (0, r_reading_until, redir);
431 redir_stack[need_here_doc++] = $$;
433 | NUMBER LESS_LESS WORD
436 $$ = make_redirection ($1, r_reading_until, redir);
437 redir_stack[need_here_doc++] = $$;
439 | LESS_LESS_LESS WORD
442 $$ = make_redirection (0, r_reading_string, redir);
444 | NUMBER LESS_LESS_LESS WORD
447 $$ = make_redirection ($1, r_reading_string, redir);
452 $$ = make_redirection (0, r_duplicating_input, redir);
454 | NUMBER LESS_AND NUMBER
457 $$ = make_redirection ($1, r_duplicating_input, redir);
462 $$ = make_redirection (1, r_duplicating_output, redir);
464 | NUMBER GREATER_AND NUMBER
467 $$ = make_redirection ($1, r_duplicating_output, redir);
472 $$ = make_redirection (0, r_duplicating_input_word, redir);
474 | NUMBER LESS_AND WORD
477 $$ = make_redirection ($1, r_duplicating_input_word, redir);
482 $$ = make_redirection (1, r_duplicating_output_word, redir);
484 | NUMBER GREATER_AND WORD
487 $$ = make_redirection ($1, r_duplicating_output_word, redir);
489 | LESS_LESS_MINUS WORD
492 $$ = make_redirection
493 (0, r_deblank_reading_until, redir);
494 redir_stack[need_here_doc++] = $$;
496 | NUMBER LESS_LESS_MINUS WORD
499 $$ = make_redirection
500 ($1, r_deblank_reading_until, redir);
501 redir_stack[need_here_doc++] = $$;
506 $$ = make_redirection (1, r_close_this, redir);
508 | NUMBER GREATER_AND '-'
511 $$ = make_redirection ($1, r_close_this, redir);
516 $$ = make_redirection (0, r_close_this, redir);
518 | NUMBER LESS_AND '-'
521 $$ = make_redirection ($1, r_close_this, redir);
526 $$ = make_redirection (1, r_err_and_out, redir);
528 | NUMBER LESS_GREATER WORD
531 $$ = make_redirection ($1, r_input_output, redir);
536 $$ = make_redirection (0, r_input_output, redir);
541 $$ = make_redirection (1, r_output_force, redir);
543 | NUMBER GREATER_BAR WORD
546 $$ = make_redirection ($1, r_output_force, redir);
550 simple_command_element: WORD
551 { $$.word = $1; $$.redirect = 0; }
553 { $$.word = $1; $$.redirect = 0; }
555 { $$.redirect = $1; $$.word = 0; }
558 redirection_list: redirection
562 | redirection_list redirection
564 register REDIRECT *t;
566 for (t = $1; t->next; t = t->next)
573 simple_command: simple_command_element
574 { $$ = make_simple_command ($1, (COMMAND *)NULL); }
575 | simple_command simple_command_element
576 { $$ = make_simple_command ($2, $1); }
579 command: simple_command
580 { $$ = clean_simple_command ($1); }
583 | shell_command redirection_list
590 register REDIRECT *t;
591 for (t = tc->redirects; t->next; t = t->next)
603 shell_command: for_command
607 | WHILE compound_list DO compound_list DONE
608 { $$ = make_while_command ($2, $4); }
609 | UNTIL compound_list DO compound_list DONE
610 { $$ = make_until_command ($2, $4); }
627 for_command: FOR WORD newline_list DO compound_list DONE
629 $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $5, word_lineno[word_top]);
630 if (word_top > 0) word_top--;
632 | FOR WORD newline_list '{' compound_list '}'
634 $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $5, word_lineno[word_top]);
635 if (word_top > 0) word_top--;
637 | FOR WORD ';' newline_list DO compound_list DONE
639 $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6, word_lineno[word_top]);
640 if (word_top > 0) word_top--;
642 | FOR WORD ';' newline_list '{' compound_list '}'
644 $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6, word_lineno[word_top]);
645 if (word_top > 0) word_top--;
647 | FOR WORD newline_list IN word_list list_terminator newline_list DO compound_list DONE
649 $$ = make_for_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9, word_lineno[word_top]);
650 if (word_top > 0) word_top--;
652 | FOR WORD newline_list IN word_list list_terminator newline_list '{' compound_list '}'
654 $$ = make_for_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9, word_lineno[word_top]);
655 if (word_top > 0) word_top--;
657 | FOR WORD newline_list IN list_terminator newline_list DO compound_list DONE
659 $$ = make_for_command ($2, (WORD_LIST *)NULL, $8, word_lineno[word_top]);
660 if (word_top > 0) word_top--;
662 | FOR WORD newline_list IN list_terminator newline_list '{' compound_list '}'
664 $$ = make_for_command ($2, (WORD_LIST *)NULL, $8, word_lineno[word_top]);
665 if (word_top > 0) word_top--;
669 arith_for_command: FOR ARITH_FOR_EXPRS list_terminator newline_list DO compound_list DONE
671 $$ = make_arith_for_command ($2, $6, arith_for_lineno);
672 if (word_top > 0) word_top--;
674 | FOR ARITH_FOR_EXPRS list_terminator newline_list '{' compound_list '}'
676 $$ = make_arith_for_command ($2, $6, arith_for_lineno);
677 if (word_top > 0) word_top--;
679 | FOR ARITH_FOR_EXPRS DO compound_list DONE
681 $$ = make_arith_for_command ($2, $4, arith_for_lineno);
682 if (word_top > 0) word_top--;
684 | FOR ARITH_FOR_EXPRS '{' compound_list '}'
686 $$ = make_arith_for_command ($2, $4, arith_for_lineno);
687 if (word_top > 0) word_top--;
691 select_command: SELECT WORD newline_list DO list DONE
693 $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $5, word_lineno[word_top]);
694 if (word_top > 0) word_top--;
696 | SELECT WORD newline_list '{' list '}'
698 $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $5, word_lineno[word_top]);
699 if (word_top > 0) word_top--;
701 | SELECT WORD ';' newline_list DO list DONE
703 $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6, word_lineno[word_top]);
704 if (word_top > 0) word_top--;
706 | SELECT WORD ';' newline_list '{' list '}'
708 $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6, word_lineno[word_top]);
709 if (word_top > 0) word_top--;
711 | SELECT WORD newline_list IN word_list list_terminator newline_list DO list DONE
713 $$ = make_select_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9, word_lineno[word_top]);
714 if (word_top > 0) word_top--;
716 | SELECT WORD newline_list IN word_list list_terminator newline_list '{' list '}'
718 $$ = make_select_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9, word_lineno[word_top]);
719 if (word_top > 0) word_top--;
723 case_command: CASE WORD newline_list IN newline_list ESAC
725 $$ = make_case_command ($2, (PATTERN_LIST *)NULL, word_lineno[word_top]);
726 if (word_top > 0) word_top--;
728 | CASE WORD newline_list IN case_clause_sequence newline_list ESAC
730 $$ = make_case_command ($2, $5, word_lineno[word_top]);
731 if (word_top > 0) word_top--;
733 | CASE WORD newline_list IN case_clause ESAC
735 $$ = make_case_command ($2, $5, word_lineno[word_top]);
736 if (word_top > 0) word_top--;
740 function_def: WORD '(' ')' newline_list function_body
741 { $$ = make_function_def ($1, $5, function_dstart, function_bstart); }
743 | FUNCTION WORD '(' ')' newline_list function_body
744 { $$ = make_function_def ($2, $6, function_dstart, function_bstart); }
746 | FUNCTION WORD newline_list function_body
747 { $$ = make_function_def ($2, $4, function_dstart, function_bstart); }
751 function_body: shell_command
753 | shell_command redirection_list
758 /* According to Posix.2 3.9.5, redirections
759 specified after the body of a function should
760 be attached to the function and performed when
761 the function is executed, not as part of the
762 function definition command. */
763 /* XXX - I don't think it matters, but we might
764 want to change this in the future to avoid
765 problems differentiating between a function
766 definition with a redirection and a function
767 definition containing a single command with a
768 redirection. The two are semantically equivalent,
769 though -- the only difference is in how the
770 command printing code displays the redirections. */
773 register REDIRECT *t;
774 for (t = tc->redirects; t->next; t = t->next)
784 subshell: '(' compound_list ')'
786 $$ = make_subshell_command ($2);
787 $$->flags |= CMD_WANT_SUBSHELL;
791 if_command: IF compound_list THEN compound_list FI
792 { $$ = make_if_command ($2, $4, (COMMAND *)NULL); }
793 | IF compound_list THEN compound_list ELSE compound_list FI
794 { $$ = make_if_command ($2, $4, $6); }
795 | IF compound_list THEN compound_list elif_clause FI
796 { $$ = make_if_command ($2, $4, $5); }
800 group_command: '{' compound_list '}'
801 { $$ = make_group_command ($2); }
804 arith_command: ARITH_CMD
805 { $$ = make_arith_command ($1); }
808 cond_command: COND_START COND_CMD COND_END
812 elif_clause: ELIF compound_list THEN compound_list
813 { $$ = make_if_command ($2, $4, (COMMAND *)NULL); }
814 | ELIF compound_list THEN compound_list ELSE compound_list
815 { $$ = make_if_command ($2, $4, $6); }
816 | ELIF compound_list THEN compound_list elif_clause
817 { $$ = make_if_command ($2, $4, $5); }
820 case_clause: pattern_list
821 | case_clause_sequence pattern_list
822 { $2->next = $1; $$ = $2; }
825 pattern_list: newline_list pattern ')' compound_list
826 { $$ = make_pattern_list ($2, $4); }
827 | newline_list pattern ')' newline_list
828 { $$ = make_pattern_list ($2, (COMMAND *)NULL); }
829 | newline_list '(' pattern ')' compound_list
830 { $$ = make_pattern_list ($3, $5); }
831 | newline_list '(' pattern ')' newline_list
832 { $$ = make_pattern_list ($3, (COMMAND *)NULL); }
835 case_clause_sequence: pattern_list SEMI_SEMI
836 | case_clause_sequence pattern_list SEMI_SEMI
837 { $2->next = $1; $$ = $2; }
841 { $$ = make_word_list ($1, (WORD_LIST *)NULL); }
843 { $$ = make_word_list ($3, $1); }
846 /* A list allows leading or trailing newlines and
847 newlines as operators (equivalent to semicolons).
848 It must end with a newline or semicolon.
849 Lists are used within commands such as if, for, while. */
851 list: newline_list list0
855 gather_here_documents ();
866 list0: list1 '\n' newline_list
867 | list1 '&' newline_list
869 if ($1->type == cm_connection)
870 $$ = connect_async_list ($1, (COMMAND *)NULL, '&');
872 $$ = command_connect ($1, (COMMAND *)NULL, '&');
874 | list1 ';' newline_list
878 list1: list1 AND_AND newline_list list1
879 { $$ = command_connect ($1, $4, AND_AND); }
880 | list1 OR_OR newline_list list1
881 { $$ = command_connect ($1, $4, OR_OR); }
882 | list1 '&' newline_list list1
884 if ($1->type == cm_connection)
885 $$ = connect_async_list ($1, $4, '&');
887 $$ = command_connect ($1, $4, '&');
889 | list1 ';' newline_list list1
890 { $$ = command_connect ($1, $4, ';'); }
891 | list1 '\n' newline_list list1
892 { $$ = command_connect ($1, $4, ';'); }
897 simple_list_terminator: '\n'
913 /* A simple_list is a list that contains no significant newlines
914 and no leading or trailing newlines. Newlines are allowed
915 only following operators, where they are not significant.
917 This is what an inputunit consists of. */
919 simple_list: simple_list1
923 gather_here_documents ();
927 if ($1->type == cm_connection)
928 $$ = connect_async_list ($1, (COMMAND *)NULL, '&');
930 $$ = command_connect ($1, (COMMAND *)NULL, '&');
932 gather_here_documents ();
938 gather_here_documents ();
942 simple_list1: simple_list1 AND_AND newline_list simple_list1
943 { $$ = command_connect ($1, $4, AND_AND); }
944 | simple_list1 OR_OR newline_list simple_list1
945 { $$ = command_connect ($1, $4, OR_OR); }
946 | simple_list1 '&' simple_list1
948 if ($1->type == cm_connection)
949 $$ = connect_async_list ($1, $3, '&');
951 $$ = command_connect ($1, $3, '&');
953 | simple_list1 ';' simple_list1
954 { $$ = command_connect ($1, $3, ';'); }
960 pipeline_command: pipeline
964 $2->flags |= CMD_INVERT_RETURN;
972 | timespec BANG pipeline
974 $3->flags |= $1|CMD_INVERT_RETURN;
977 | BANG timespec pipeline
979 $3->flags |= $2|CMD_INVERT_RETURN;
982 | timespec list_terminator
986 /* Boy, this is unclean. `time' by itself can
987 time a null command. We cheat and push a
988 newline back if the list_terminator was a newline
989 to avoid the double-newline problem (one to
990 terminate this, one to terminate the command) */
993 $$ = make_simple_command (x, (COMMAND *)NULL);
995 /* XXX - let's cheat and push a newline back */
997 token_to_read = '\n';
1003 pipeline '|' newline_list pipeline
1004 { $$ = command_connect ($1, $4, '|'); }
1010 { $$ = CMD_TIME_PIPELINE; }
1012 { $$ = CMD_TIME_PIPELINE|CMD_TIME_POSIX; }
1016 /* Possible states for the parser that require it to do special things. */
1017 #define PST_CASEPAT 0x0001 /* in a case pattern list */
1018 #define PST_ALEXPNEXT 0x0002 /* expand next word for aliases */
1019 #define PST_ALLOWOPNBRC 0x0004 /* allow open brace for function def */
1020 #define PST_NEEDCLOSBRC 0x0008 /* need close brace */
1021 #define PST_DBLPAREN 0x0010 /* double-paren parsing */
1022 #define PST_SUBSHELL 0x0020 /* ( ... ) subshell */
1023 #define PST_CMDSUBST 0x0040 /* $( ... ) command substitution */
1024 #define PST_CASESTMT 0x0080 /* parsing a case statement */
1025 #define PST_CONDCMD 0x0100 /* parsing a [[...]] command */
1026 #define PST_CONDEXPR 0x0200 /* parsing the guts of [[...]] */
1027 #define PST_ARITHFOR 0x0400 /* parsing an arithmetic for command */
1028 #define PST_ALEXPAND 0x0800 /* OK to expand aliases - unused */
1029 #define PST_CMDTOKEN 0x1000 /* command token OK - unused */
1030 #define PST_COMPASSIGN 0x2000 /* parsing x=(...) compound assignment */
1032 /* Initial size to allocate for tokens, and the
1033 amount to grow them by. */
1034 #define TOKEN_DEFAULT_INITIAL_SIZE 496
1035 #define TOKEN_DEFAULT_GROW_SIZE 512
1037 /* Should we call prompt_again? */
1038 #define SHOULD_PROMPT() \
1039 (interactive && (bash_input.type == st_stdin || bash_input.type == st_stream))
1042 # define expanding_alias() (pushed_string_list && pushed_string_list->expander)
1044 # define expanding_alias() 0
1047 /* The token currently being read. */
1048 static int current_token;
1050 /* The last read token, or NULL. read_token () uses this for context
1052 static int last_read_token;
1054 /* The token read prior to last_read_token. */
1055 static int token_before_that;
1057 /* The token read prior to token_before_that. */
1058 static int two_tokens_ago;
1060 /* The current parser state. */
1061 static int parser_state;
1063 /* Global var is non-zero when end of file has been reached. */
1064 int EOF_Reached = 0;
1077 /* yy_getc () returns the next available character from input or EOF.
1078 yy_ungetc (c) makes `c' the next character to read.
1079 init_yy_io (get, unget, type, location) makes the function GET the
1080 installed function for getting the next character, makes UNGET the
1081 installed function for un-getting a character, sets the type of stream
1082 (either string or file) from TYPE, and makes LOCATION point to where
1083 the input is coming from. */
1085 /* Unconditionally returns end-of-file. */
1092 /* Variable containing the current get and unget functions.
1093 See ./input.h for a clearer description. */
1094 BASH_INPUT bash_input;
1096 /* Set all of the fields in BASH_INPUT to NULL. Free bash_input.name if it
1097 is non-null, avoiding a memory leak. */
1099 initialize_bash_input ()
1101 bash_input.type = st_none;
1102 FREE (bash_input.name);
1103 bash_input.name = (char *)NULL;
1104 bash_input.location.file = (FILE *)NULL;
1105 bash_input.location.string = (char *)NULL;
1106 bash_input.getter = (sh_cget_func_t *)NULL;
1107 bash_input.ungetter = (sh_cunget_func_t *)NULL;
1110 /* Set the contents of the current bash input stream from
1111 GET, UNGET, TYPE, NAME, and LOCATION. */
1113 init_yy_io (get, unget, type, name, location)
1114 sh_cget_func_t *get;
1115 sh_cunget_func_t *unget;
1116 enum stream_type type;
1118 INPUT_STREAM location;
1120 bash_input.type = type;
1121 FREE (bash_input.name);
1122 bash_input.name = name ? savestring (name) : (char *)NULL;
1126 memcpy((char *)&bash_input.location.string, (char *)&location.string, sizeof(location));
1128 bash_input.location = location;
1130 bash_input.getter = get;
1131 bash_input.ungetter = unget;
1137 return (bash_input.name ? bash_input.name : "stdin");
1140 /* Call this to get the next character of input. */
1144 return (*(bash_input.getter)) ();
1147 /* Call this to unget C. That is, to make C the next character
1153 return (*(bash_input.ungetter)) (c);
1156 #if defined (BUFFERED_INPUT)
1157 #ifdef INCLUDE_UNUSED
1159 input_file_descriptor ()
1161 switch (bash_input.type)
1164 return (fileno (bash_input.location.file));
1166 return (bash_input.location.buffered_fd);
1169 return (fileno (stdin));
1173 #endif /* BUFFERED_INPUT */
1175 /* **************************************************************** */
1177 /* Let input be read from readline (). */
1179 /* **************************************************************** */
1181 #if defined (READLINE)
1182 char *current_readline_prompt = (char *)NULL;
1183 char *current_readline_line = (char *)NULL;
1184 int current_readline_line_index = 0;
1189 SigHandler *old_sigint;
1193 if (!current_readline_line)
1195 if (!bash_readline_initialized)
1196 initialize_readline ();
1198 #if defined (JOB_CONTROL)
1200 give_terminal_to (shell_pgrp, 0);
1201 #endif /* JOB_CONTROL */
1203 old_sigint = (SigHandler *)NULL;
1204 if (signal_is_ignored (SIGINT) == 0)
1206 old_sigint = (SigHandler *)set_signal_handler (SIGINT, sigint_sighandler);
1207 interrupt_immediately++;
1210 current_readline_line = readline (current_readline_prompt ?
1211 current_readline_prompt : "");
1213 if (signal_is_ignored (SIGINT) == 0 && old_sigint)
1215 interrupt_immediately--;
1216 set_signal_handler (SIGINT, old_sigint);
1220 /* Reset the prompt to the decoded value of prompt_string_pointer. */
1221 reset_readline_prompt ();
1224 if (current_readline_line == 0)
1227 current_readline_line_index = 0;
1228 line_len = strlen (current_readline_line);
1230 current_readline_line = (char *)xrealloc (current_readline_line, 2 + line_len);
1231 current_readline_line[line_len++] = '\n';
1232 current_readline_line[line_len] = '\0';
1235 if (current_readline_line[current_readline_line_index] == 0)
1237 free (current_readline_line);
1238 current_readline_line = (char *)NULL;
1239 return (yy_readline_get ());
1243 c = current_readline_line[current_readline_line_index++];
1249 yy_readline_unget (c)
1252 if (current_readline_line_index && current_readline_line)
1253 current_readline_line[--current_readline_line_index] = c;
1258 with_input_from_stdin ()
1260 INPUT_STREAM location;
1262 if (bash_input.type != st_stdin && stream_on_stack (st_stdin) == 0)
1264 location.string = current_readline_line;
1265 init_yy_io (yy_readline_get, yy_readline_unget,
1266 st_stdin, "readline stdin", location);
1270 #else /* !READLINE */
1273 with_input_from_stdin ()
1275 with_input_from_stream (stdin, "stdin");
1277 #endif /* !READLINE */
1279 /* **************************************************************** */
1281 /* Let input come from STRING. STRING is zero terminated. */
1283 /* **************************************************************** */
1288 register char *string;
1289 register unsigned char c;
1291 string = bash_input.location.string;
1293 /* If the string doesn't exist, or is empty, EOF found. */
1294 if (string && *string)
1297 bash_input.location.string = string;
1308 *(--bash_input.location.string) = c;
1313 with_input_from_string (string, name)
1317 INPUT_STREAM location;
1319 location.string = string;
1320 init_yy_io (yy_string_get, yy_string_unget, st_string, name, location);
1323 /* **************************************************************** */
1325 /* Let input come from STREAM. */
1327 /* **************************************************************** */
1329 /* These two functions used to test the value of the HAVE_RESTARTABLE_SYSCALLS
1330 define, and just use getc/ungetc if it was defined, but since bash
1331 installs its signal handlers without the SA_RESTART flag, some signals
1332 (like SIGCHLD, SIGWINCH, etc.) received during a read(2) will not cause
1333 the read to be restarted. We need to restart it ourselves. */
1341 if (bash_input.location.file)
1342 result = getc_with_restart (bash_input.location.file);
1351 return (ungetc_with_restart (c, bash_input.location.file));
1355 with_input_from_stream (stream, name)
1359 INPUT_STREAM location;
1361 location.file = stream;
1362 init_yy_io (yy_stream_get, yy_stream_unget, st_stream, name, location);
1365 typedef struct stream_saver {
1366 struct stream_saver *next;
1367 BASH_INPUT bash_input;
1369 #if defined (BUFFERED_INPUT)
1370 BUFFERED_STREAM *bstream;
1371 #endif /* BUFFERED_INPUT */
1374 /* The globally known line number. */
1375 int line_number = 0;
1377 #if defined (COND_COMMAND)
1378 static int cond_lineno;
1379 static int cond_token;
1382 STREAM_SAVER *stream_list = (STREAM_SAVER *)NULL;
1385 push_stream (reset_lineno)
1388 STREAM_SAVER *saver = (STREAM_SAVER *)xmalloc (sizeof (STREAM_SAVER));
1390 xbcopy ((char *)&bash_input, (char *)&(saver->bash_input), sizeof (BASH_INPUT));
1392 #if defined (BUFFERED_INPUT)
1393 saver->bstream = (BUFFERED_STREAM *)NULL;
1394 /* If we have a buffered stream, clear out buffers[fd]. */
1395 if (bash_input.type == st_bstream && bash_input.location.buffered_fd >= 0)
1396 saver->bstream = set_buffered_stream (bash_input.location.buffered_fd,
1397 (BUFFERED_STREAM *)NULL);
1398 #endif /* BUFFERED_INPUT */
1400 saver->line = line_number;
1401 bash_input.name = (char *)NULL;
1402 saver->next = stream_list;
1403 stream_list = saver;
1416 STREAM_SAVER *saver = stream_list;
1419 stream_list = stream_list->next;
1421 init_yy_io (saver->bash_input.getter,
1422 saver->bash_input.ungetter,
1423 saver->bash_input.type,
1424 saver->bash_input.name,
1425 saver->bash_input.location);
1427 #if defined (BUFFERED_INPUT)
1428 /* If we have a buffered stream, restore buffers[fd]. */
1429 /* If the input file descriptor was changed while this was on the
1430 save stack, update the buffered fd to the new file descriptor and
1431 re-establish the buffer <-> bash_input fd correspondence. */
1432 if (bash_input.type == st_bstream && bash_input.location.buffered_fd >= 0)
1434 if (bash_input_fd_changed)
1436 bash_input_fd_changed = 0;
1437 if (default_buffered_input >= 0)
1439 bash_input.location.buffered_fd = default_buffered_input;
1440 saver->bstream->b_fd = default_buffered_input;
1441 SET_CLOSE_ON_EXEC (default_buffered_input);
1444 /* XXX could free buffered stream returned as result here. */
1445 set_buffered_stream (bash_input.location.buffered_fd, saver->bstream);
1447 #endif /* BUFFERED_INPUT */
1449 line_number = saver->line;
1451 FREE (saver->bash_input.name);
1456 /* Return 1 if a stream of type TYPE is saved on the stack. */
1458 stream_on_stack (type)
1459 enum stream_type type;
1461 register STREAM_SAVER *s;
1463 for (s = stream_list; s; s = s->next)
1464 if (s->bash_input.type == type)
1469 /* Save the current token state and return it in a malloced array. */
1475 ret = (int *)xmalloc (3 * sizeof (int));
1476 ret[0] = last_read_token;
1477 ret[1] = token_before_that;
1478 ret[2] = two_tokens_ago;
1483 restore_token_state (ts)
1488 last_read_token = ts[0];
1489 token_before_that = ts[1];
1490 two_tokens_ago = ts[2];
1494 * This is used to inhibit alias expansion and reserved word recognition
1495 * inside case statement pattern lists. A `case statement pattern list' is:
1497 * everything between the `in' in a `case word in' and the next ')'
1499 * everything between a `;;' and the next `)' or `esac'
1502 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
1504 #define END_OF_ALIAS 0
1507 * Pseudo-global variables used in implementing token-wise alias expansion.
1511 * Pushing and popping strings. This works together with shell_getc to
1512 * implement alias expansion on a per-token basis.
1515 typedef struct string_saver {
1516 struct string_saver *next;
1517 int expand_alias; /* Value to set expand_alias to when string is popped. */
1520 alias_t *expander; /* alias that caused this line to be pushed. */
1522 int saved_line_size, saved_line_index, saved_line_terminator;
1525 STRING_SAVER *pushed_string_list = (STRING_SAVER *)NULL;
1528 * Push the current shell_input_line onto a stack of such lines and make S
1529 * the current input. Used when expanding aliases. EXPAND is used to set
1530 * the value of expand_next_token when the string is popped, so that the
1531 * word after the alias in the original line is handled correctly when the
1532 * alias expands to multiple words. TOKEN is the token that was expanded
1533 * into S; it is saved and used to prevent infinite recursive expansion.
1536 push_string (s, expand, ap)
1541 STRING_SAVER *temp = (STRING_SAVER *)xmalloc (sizeof (STRING_SAVER));
1543 temp->expand_alias = expand;
1544 temp->saved_line = shell_input_line;
1545 temp->saved_line_size = shell_input_line_size;
1546 temp->saved_line_index = shell_input_line_index;
1547 temp->saved_line_terminator = shell_input_line_terminator;
1549 temp->expander = ap;
1551 temp->next = pushed_string_list;
1552 pushed_string_list = temp;
1556 ap->flags |= AL_BEINGEXPANDED;
1559 shell_input_line = s;
1560 shell_input_line_size = strlen (s);
1561 shell_input_line_index = 0;
1562 shell_input_line_terminator = '\0';
1564 parser_state &= ~PST_ALEXPNEXT; /* XXX */
1567 set_line_mbstate ();
1571 * Make the top of the pushed_string stack be the current shell input.
1572 * Only called when there is something on the stack. Called from shell_getc
1573 * when it thinks it has consumed the string generated by an alias expansion
1574 * and needs to return to the original input line.
1581 FREE (shell_input_line);
1582 shell_input_line = pushed_string_list->saved_line;
1583 shell_input_line_index = pushed_string_list->saved_line_index;
1584 shell_input_line_size = pushed_string_list->saved_line_size;
1585 shell_input_line_terminator = pushed_string_list->saved_line_terminator;
1587 if (pushed_string_list->expand_alias)
1588 parser_state |= PST_ALEXPNEXT;
1590 parser_state &= ~PST_ALEXPNEXT;
1592 t = pushed_string_list;
1593 pushed_string_list = pushed_string_list->next;
1597 t->expander->flags &= ~AL_BEINGEXPANDED;
1602 set_line_mbstate ();
1608 register STRING_SAVER *t, *t1;
1610 for (t = pushed_string_list; t; )
1613 FREE (t->saved_line);
1616 t->expander->flags &= ~AL_BEINGEXPANDED;
1621 pushed_string_list = (STRING_SAVER *)NULL;
1624 #endif /* ALIAS || DPAREN_ARITHMETIC */
1627 free_pushed_string_input ()
1629 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
1630 free_string_list ();
1634 /* Return a line of text, taken from wherever yylex () reads input.
1635 If there is no more input, then we return NULL. If REMOVE_QUOTED_NEWLINE
1636 is non-zero, we remove unquoted \<newline> pairs. This is used by
1637 read_secondary_line to read here documents. */
1639 read_a_line (remove_quoted_newline)
1640 int remove_quoted_newline;
1642 static char *line_buffer = (char *)NULL;
1643 static int buffer_size = 0;
1644 int indx = 0, c, peekc, pass_next;
1646 #if defined (READLINE)
1647 if (no_line_editing && SHOULD_PROMPT ())
1649 if (SHOULD_PROMPT ())
1658 /* Allow immediate exit if interrupted during input. */
1661 /* Ignore null bytes in input. */
1665 internal_warning ("read_a_line: ignored null byte in input");
1670 /* If there is no more input, then we return NULL. */
1673 if (interactive && bash_input.type == st_stream)
1676 return ((char *)NULL);
1680 /* `+2' in case the final character in the buffer is a newline. */
1681 RESIZE_MALLOCED_BUFFER (line_buffer, indx, 2, buffer_size, 128);
1683 /* IF REMOVE_QUOTED_NEWLINES is non-zero, we are reading a
1684 here document with an unquoted delimiter. In this case,
1685 the line will be expanded as if it were in double quotes.
1686 We allow a backslash to escape the next character, but we
1687 need to treat the backslash specially only if a backslash
1688 quoting a backslash-newline pair appears in the line. */
1691 line_buffer[indx++] = c;
1694 else if (c == '\\' && remove_quoted_newline)
1700 continue; /* Make the unquoted \<newline> pair disappear. */
1706 line_buffer[indx++] = c; /* Preserve the backslash. */
1710 line_buffer[indx++] = c;
1714 line_buffer[indx] = '\0';
1715 return (line_buffer);
1720 /* Return a line as in read_a_line (), but insure that the prompt is
1721 the secondary prompt. This is used to read the lines of a here
1722 document. REMOVE_QUOTED_NEWLINE is non-zero if we should remove
1723 newlines quoted with backslashes while reading the line. It is
1724 non-zero unless the delimiter of the here document was quoted. */
1726 read_secondary_line (remove_quoted_newline)
1727 int remove_quoted_newline;
1729 prompt_string_pointer = &ps2_prompt;
1730 if (SHOULD_PROMPT())
1732 return (read_a_line (remove_quoted_newline));
1735 /* **************************************************************** */
1739 /* **************************************************************** */
1741 /* Reserved words. These are only recognized as the first word of a
1743 STRING_INT_ALIST word_token_alist[] = {
1752 #if defined (SELECT_COMMAND)
1753 { "select", SELECT },
1760 { "function", FUNCTION },
1761 #if defined (COMMAND_TIMING)
1767 #if defined (COND_COMMAND)
1768 { "[[", COND_START },
1774 /* other tokens that can be returned by read_token() */
1775 STRING_INT_ALIST other_token_alist[] = {
1776 /* Multiple-character tokens with special values */
1780 { ">>", GREATER_GREATER },
1781 { "<<", LESS_LESS },
1783 { ">&", GREATER_AND },
1784 { ";;", SEMI_SEMI },
1785 { "<<-", LESS_LESS_MINUS },
1786 { "<<<", LESS_LESS_LESS },
1787 { "&>", AND_GREATER },
1788 { "<>", LESS_GREATER },
1789 { ">|", GREATER_BAR },
1790 { "EOF", yacc_EOF },
1791 /* Tokens whose value is the character itself */
1802 { "newline", '\n' },
1806 /* others not listed here:
1807 WORD look at yylval.word
1808 ASSIGNMENT_WORD look at yylval.word
1809 NUMBER look at yylval.number
1810 ARITH_CMD look at yylval.word_list
1811 ARITH_FOR_EXPRS look at yylval.word_list
1812 COND_CMD look at yylval.command
1815 /* These are used by read_token_word, but appear up here so that shell_getc
1816 can use them to decide when to add otherwise blank lines to the history. */
1818 /* The primary delimiter stack. */
1819 struct dstack dstack = { (char *)NULL, 0, 0 };
1821 /* A temporary delimiter stack to be used when decoding prompt strings.
1822 This is needed because command substitutions in prompt strings (e.g., PS2)
1823 can screw up the parser's quoting state. */
1824 static struct dstack temp_dstack = { (char *)NULL, 0, 0 };
1826 /* Macro for accessing the top delimiter on the stack. Returns the
1827 delimiter or zero if none. */
1828 #define current_delimiter(ds) \
1829 (ds.delimiter_depth ? ds.delimiters[ds.delimiter_depth - 1] : 0)
1831 #define push_delimiter(ds, character) \
1834 if (ds.delimiter_depth + 2 > ds.delimiter_space) \
1835 ds.delimiters = (char *)xrealloc \
1836 (ds.delimiters, (ds.delimiter_space += 10) * sizeof (char)); \
1837 ds.delimiters[ds.delimiter_depth] = character; \
1838 ds.delimiter_depth++; \
1842 #define pop_delimiter(ds) ds.delimiter_depth--
1844 /* Return the next shell input character. This always reads characters
1845 from shell_input_line; when that line is exhausted, it is time to
1846 read the next line. This is called by read_token when the shell is
1847 processing normal command input. */
1849 /* This implements one-character lookahead/lookbehind across physical input
1850 lines, to avoid something being lost because it's pushed back with
1851 shell_ungetc when we're at the start of a line. */
1852 static int eol_ungetc_lookahead = 0;
1855 shell_getc (remove_quoted_newline)
1856 int remove_quoted_newline;
1861 static int mustpop = 0;
1865 if (eol_ungetc_lookahead)
1867 c = eol_ungetc_lookahead;
1868 eol_ungetc_lookahead = 0;
1872 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
1873 /* If shell_input_line[shell_input_line_index] == 0, but there is
1874 something on the pushed list of strings, then we don't want to go
1875 off and get another line. We let the code down below handle it. */
1877 if (!shell_input_line || ((!shell_input_line[shell_input_line_index]) &&
1878 (pushed_string_list == (STRING_SAVER *)NULL)))
1879 #else /* !ALIAS && !DPAREN_ARITHMETIC */
1880 if (!shell_input_line || !shell_input_line[shell_input_line_index])
1881 #endif /* !ALIAS && !DPAREN_ARITHMETIC */
1887 /* Allow immediate exit if interrupted during input. */
1891 shell_input_line_terminator = 0;
1893 /* If the shell is interatctive, but not currently printing a prompt
1894 (interactive_shell && interactive == 0), we don't want to print
1895 notifies or cleanup the jobs -- we want to defer it until we do
1896 print the next prompt. */
1897 if (interactive_shell == 0 || SHOULD_PROMPT())
1899 #if defined (JOB_CONTROL)
1900 /* This can cause a problem when reading a command as the result
1901 of a trap, when the trap is called from flush_child. This call
1902 had better not cause jobs to disappear from the job table in
1903 that case, or we will have big trouble. */
1904 notify_and_cleanup ();
1905 #else /* !JOB_CONTROL */
1906 cleanup_dead_jobs ();
1907 #endif /* !JOB_CONTROL */
1910 #if defined (READLINE)
1911 if (no_line_editing && SHOULD_PROMPT())
1913 if (SHOULD_PROMPT())
1917 if (bash_input.type == st_stream)
1924 /* Allow immediate exit if interrupted during input. */
1930 internal_warning ("shell_getc: ignored null byte in input");
1935 RESIZE_MALLOCED_BUFFER (shell_input_line, i, 2, shell_input_line_size, 256);
1939 if (bash_input.type == st_stream)
1943 shell_input_line_terminator = EOF;
1945 shell_input_line[i] = '\0';
1949 shell_input_line[i++] = c;
1953 shell_input_line[--i] = '\0';
1954 current_command_line_count++;
1959 shell_input_line_index = 0;
1960 shell_input_line_len = i; /* == strlen (shell_input_line) */
1962 set_line_mbstate ();
1964 #if defined (HISTORY)
1965 if (remember_on_history && shell_input_line && shell_input_line[0])
1968 # if defined (BANG_HISTORY)
1971 /* If the current delimiter is a single quote, we should not be
1972 performing history expansion, even if we're on a different
1973 line from the original single quote. */
1974 old_hist = history_expansion_inhibited;
1975 if (current_delimiter (dstack) == '\'')
1976 history_expansion_inhibited = 1;
1978 expansions = pre_process_line (shell_input_line, 1, 1);
1979 # if defined (BANG_HISTORY)
1980 history_expansion_inhibited = old_hist;
1982 if (expansions != shell_input_line)
1984 free (shell_input_line);
1985 shell_input_line = expansions;
1986 shell_input_line_len = shell_input_line ?
1987 strlen (shell_input_line) : 0;
1988 if (!shell_input_line_len)
1989 current_command_line_count--;
1991 /* We have to force the xrealloc below because we don't know
1992 the true allocated size of shell_input_line anymore. */
1993 shell_input_line_size = shell_input_line_len;
1995 set_line_mbstate ();
1998 /* Try to do something intelligent with blank lines encountered while
1999 entering multi-line commands. XXX - this is grotesque */
2000 else if (remember_on_history && shell_input_line &&
2001 shell_input_line[0] == '\0' &&
2002 current_command_line_count > 1)
2004 if (current_delimiter (dstack))
2005 /* We know shell_input_line[0] == 0 and we're reading some sort of
2006 quoted string. This means we've got a line consisting of only
2007 a newline in a quoted string. We want to make sure this line
2008 gets added to the history. */
2009 maybe_add_history (shell_input_line);
2013 hdcs = history_delimiting_chars ();
2014 if (hdcs && hdcs[0] == ';')
2015 maybe_add_history (shell_input_line);
2019 #endif /* HISTORY */
2021 if (shell_input_line)
2023 /* Lines that signify the end of the shell's input should not be
2025 if (echo_input_at_read && (shell_input_line[0] ||
2026 shell_input_line_terminator != EOF))
2027 fprintf (stderr, "%s\n", shell_input_line);
2031 shell_input_line_size = 0;
2032 prompt_string_pointer = ¤t_prompt_string;
2033 if (SHOULD_PROMPT ())
2038 /* Add the newline to the end of this string, iff the string does
2039 not already end in an EOF character. */
2040 if (shell_input_line_terminator != EOF)
2042 if (shell_input_line_len + 3 > shell_input_line_size)
2043 shell_input_line = (char *)xrealloc (shell_input_line,
2044 1 + (shell_input_line_size += 2));
2046 shell_input_line[shell_input_line_len] = '\n';
2047 shell_input_line[shell_input_line_len + 1] = '\0';
2049 set_line_mbstate ();
2053 uc = shell_input_line[shell_input_line_index];
2056 shell_input_line_index++;
2058 if MBTEST(uc == '\\' && remove_quoted_newline && shell_input_line[shell_input_line_index] == '\n')
2060 if (SHOULD_PROMPT ())
2066 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
2067 /* If UC is NULL, we have reached the end of the current input string. If
2068 pushed_string_list is non-empty, it's time to pop to the previous string
2069 because we have fully consumed the result of the last alias expansion.
2070 Do it transparently; just return the next character of the string popped
2072 if (!uc && (pushed_string_list != (STRING_SAVER *)NULL))
2075 uc = shell_input_line[shell_input_line_index];
2077 shell_input_line_index++;
2079 #endif /* ALIAS || DPAREN_ARITHMETIC */
2081 if (!uc && shell_input_line_terminator == EOF)
2082 return ((shell_input_line_index != 0) ? '\n' : EOF);
2087 /* Put C back into the input for the shell. This might need changes for
2088 HANDLE_MULTIBYTE around EOLs. Since we (currently) never push back a
2089 character different than we read, shell_input_line_property doesn't need
2090 to change when manipulating shell_input_line. The define for
2091 last_shell_getc_is_singlebyte should take care of it, though. */
2096 if (shell_input_line && shell_input_line_index)
2097 shell_input_line[--shell_input_line_index] = c;
2099 eol_ungetc_lookahead = c;
2102 #ifdef INCLUDE_UNUSED
2103 /* Back the input pointer up by one, effectively `ungetting' a character. */
2107 if (shell_input_line && shell_input_line_index)
2108 shell_input_line_index--;
2112 /* Discard input until CHARACTER is seen, then push that character back
2113 onto the input stream. */
2115 discard_until (character)
2120 while ((c = shell_getc (0)) != EOF && c != character)
2128 execute_prompt_command (command)
2132 sh_parser_state_t ps;
2134 save_parser_state (&ps);
2135 last_lastarg = get_string_value ("_");
2137 last_lastarg = savestring (last_lastarg);
2139 parse_and_execute (savestring (command), "PROMPT_COMMAND", SEVAL_NONINT|SEVAL_NOHIST);
2141 restore_parser_state (&ps);
2142 bind_variable ("_", last_lastarg);
2143 FREE (last_lastarg);
2145 if (token_to_read == '\n') /* reset_parser was called */
2149 /* Place to remember the token. We try to keep the buffer
2150 at a reasonable size, but it can grow. */
2151 static char *token = (char *)NULL;
2153 /* Current size of the token buffer. */
2154 static int token_buffer_size;
2156 /* Command to read_token () explaining what we want it to do. */
2159 #define prompt_is_ps1 \
2160 (!prompt_string_pointer || prompt_string_pointer == &ps1_prompt)
2162 /* Function for yyparse to call. yylex keeps track of
2163 the last two tokens read, and calls read_token. */
2167 if (interactive && (current_token == 0 || current_token == '\n'))
2169 /* Before we print a prompt, we might have to check mailboxes.
2170 We do this only if it is time to do so. Notice that only here
2171 is the mail alarm reset; nothing takes place in check_mail ()
2172 except the checking of mail. Please don't change this. */
2173 if (prompt_is_ps1 && time_to_check_mail ())
2176 reset_mail_timer ();
2179 /* Avoid printing a prompt if we're not going to read anything, e.g.
2180 after resetting the parser with read_token (RESET). */
2181 if (token_to_read == 0 && SHOULD_PROMPT ())
2185 two_tokens_ago = token_before_that;
2186 token_before_that = last_read_token;
2187 last_read_token = current_token;
2188 current_token = read_token (READ);
2189 return (current_token);
2192 /* When non-zero, we have read the required tokens
2193 which allow ESAC to be the next one read. */
2194 static int esacs_needed_count;
2197 gather_here_documents ()
2200 while (need_here_doc)
2202 make_here_document (redir_stack[r++]);
2207 /* When non-zero, an open-brace used to create a group is awaiting a close
2209 static int open_brace_count;
2211 #define command_token_position(token) \
2212 (((token) == ASSIGNMENT_WORD) || \
2213 ((token) != SEMI_SEMI && reserved_word_acceptable(token)))
2215 #define assignment_acceptable(token) \
2216 (command_token_position(token) && ((parser_state & PST_CASEPAT) == 0))
2218 /* Check to see if TOKEN is a reserved word and return the token
2220 #define CHECK_FOR_RESERVED_WORD(tok) \
2222 if (!dollar_present && !quoted && \
2223 reserved_word_acceptable (last_read_token)) \
2226 for (i = 0; word_token_alist[i].word != (char *)NULL; i++) \
2227 if (STREQ (tok, word_token_alist[i].word)) \
2229 if ((parser_state & PST_CASEPAT) && (word_token_alist[i].token != ESAC)) \
2231 if (word_token_alist[i].token == TIME && time_command_acceptable () == 0) \
2233 if (word_token_alist[i].token == ESAC) \
2234 parser_state &= ~(PST_CASEPAT|PST_CASESTMT); \
2235 else if (word_token_alist[i].token == CASE) \
2236 parser_state |= PST_CASESTMT; \
2237 else if (word_token_alist[i].token == COND_END) \
2238 parser_state &= ~(PST_CONDCMD|PST_CONDEXPR); \
2239 else if (word_token_alist[i].token == COND_START) \
2240 parser_state |= PST_CONDCMD; \
2241 else if (word_token_alist[i].token == '{') \
2242 open_brace_count++; \
2243 else if (word_token_alist[i].token == '}' && open_brace_count) \
2244 open_brace_count--; \
2245 return (word_token_alist[i].token); \
2252 /* OK, we have a token. Let's try to alias expand it, if (and only if)
2255 It is eligible for expansion if EXPAND_ALIASES is set, and
2256 the token is unquoted and the last token read was a command
2257 separator (or expand_next_token is set), and we are currently
2258 processing an alias (pushed_string_list is non-empty) and this
2259 token is not the same as the current or any previously
2262 Special cases that disqualify:
2263 In a pattern list in a case statement (parser_state & PST_CASEPAT). */
2273 r = xmalloc (l + 2);
2282 alias_expand_token (tokstr)
2288 if (((parser_state & PST_ALEXPNEXT) || command_token_position (last_read_token)) &&
2289 (parser_state & PST_CASEPAT) == 0)
2291 ap = find_alias (tokstr);
2293 /* Currently expanding this token. */
2294 if (ap && (ap->flags & AL_BEINGEXPANDED))
2295 return (NO_EXPANSION);
2297 /* mk_alexpansion puts an extra space on the end of the alias expansion,
2298 so the lookahead by the parser works right. If this gets changed,
2299 make sure the code in shell_getc that deals with reaching the end of
2300 an expanded alias is changed with it. */
2301 expanded = ap ? mk_alexpansion (ap->value) : (char *)NULL;
2305 push_string (expanded, ap->flags & AL_EXPANDNEXT, ap);
2306 return (RE_READ_TOKEN);
2309 /* This is an eligible token that does not have an expansion. */
2310 return (NO_EXPANSION);
2312 return (NO_EXPANSION);
2317 time_command_acceptable ()
2319 #if defined (COMMAND_TIMING)
2320 switch (last_read_token)
2339 #endif /* COMMAND_TIMING */
2342 /* Handle special cases of token recognition:
2343 IN is recognized if the last token was WORD and the token
2344 before that was FOR or CASE or SELECT.
2346 DO is recognized if the last token was WORD and the token
2347 before that was FOR or SELECT.
2349 ESAC is recognized if the last token caused `esacs_needed_count'
2352 `{' is recognized if the last token as WORD and the token
2353 before that was FUNCTION, or if we just parsed an arithmetic
2356 `}' is recognized if there is an unclosed `{' present.
2358 `-p' is returned as TIMEOPT if the last read token was TIME.
2360 ']]' is returned as COND_END if the parser is currently parsing
2361 a conditional expression ((parser_state & PST_CONDEXPR) != 0)
2363 `time' is returned as TIME if and only if it is immediately
2364 preceded by one of `;', `\n', `||', `&&', or `&'.
2368 special_case_tokens (tokstr)
2371 if ((last_read_token == WORD) &&
2372 #if defined (SELECT_COMMAND)
2373 ((token_before_that == FOR) || (token_before_that == CASE) || (token_before_that == SELECT)) &&
2375 ((token_before_that == FOR) || (token_before_that == CASE)) &&
2377 (tokstr[0] == 'i' && tokstr[1] == 'n' && tokstr[2] == 0))
2379 if (token_before_that == CASE)
2381 parser_state |= PST_CASEPAT;
2382 esacs_needed_count++;
2387 if (last_read_token == WORD &&
2388 #if defined (SELECT_COMMAND)
2389 (token_before_that == FOR || token_before_that == SELECT) &&
2391 (token_before_that == FOR) &&
2393 (tokstr[0] == 'd' && tokstr[1] == 'o' && tokstr[2] == '\0'))
2396 /* Ditto for ESAC in the CASE case.
2397 Specifically, this handles "case word in esac", which is a legal
2398 construct, certainly because someone will pass an empty arg to the
2399 case construct, and we don't want it to barf. Of course, we should
2400 insist that the case construct has at least one pattern in it, but
2401 the designers disagree. */
2402 if (esacs_needed_count)
2404 esacs_needed_count--;
2405 if (STREQ (tokstr, "esac"))
2407 parser_state &= ~PST_CASEPAT;
2412 /* The start of a shell function definition. */
2413 if (parser_state & PST_ALLOWOPNBRC)
2415 parser_state &= ~PST_ALLOWOPNBRC;
2416 if (tokstr[0] == '{' && tokstr[1] == '\0') /* } */
2419 function_bstart = line_number;
2420 return ('{'); /* } */
2424 /* We allow a `do' after a for ((...)) without an intervening
2426 if (last_read_token == ARITH_FOR_EXPRS && tokstr[0] == 'd' && tokstr[1] == 'o' && !tokstr[2])
2428 if (last_read_token == ARITH_FOR_EXPRS && tokstr[0] == '{' && tokstr[1] == '\0') /* } */
2431 return ('{'); /* } */
2434 if (open_brace_count && reserved_word_acceptable (last_read_token) && tokstr[0] == '}' && !tokstr[1])
2436 open_brace_count--; /* { */
2440 #if defined (COMMAND_TIMING)
2441 /* Handle -p after `time'. */
2442 if (last_read_token == TIME && tokstr[0] == '-' && tokstr[1] == 'p' && !tokstr[2])
2447 #if defined (COMMAND_TIMING)
2448 if (STREQ (token, "time") && ((parser_state & PST_CASEPAT) == 0) && time_command_acceptable ())
2450 #endif /* COMMAND_TIMING */
2453 #if defined (COND_COMMAND) /* [[ */
2454 if ((parser_state & PST_CONDEXPR) && tokstr[0] == ']' && tokstr[1] == ']' && tokstr[2] == '\0')
2461 /* Called from shell.c when Control-C is typed at top level. Or
2462 by the error rule at top level. */
2466 dstack.delimiter_depth = 0; /* No delimiters found so far. */
2467 open_brace_count = 0;
2471 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
2472 if (pushed_string_list)
2473 free_string_list ();
2474 #endif /* ALIAS || DPAREN_ARITHMETIC */
2476 if (shell_input_line)
2478 free (shell_input_line);
2479 shell_input_line = (char *)NULL;
2480 shell_input_line_size = shell_input_line_index = 0;
2483 FREE (word_desc_to_read);
2484 word_desc_to_read = (WORD_DESC *)NULL;
2486 last_read_token = '\n';
2487 token_to_read = '\n';
2490 /* Read the next token. Command can be READ (normal operation) or
2491 RESET (to normalize state). */
2493 read_token (command)
2496 int character; /* Current character. */
2497 int peek_char; /* Temporary look-ahead character. */
2498 int result; /* The thing to return. */
2500 if (command == RESET)
2508 result = token_to_read;
2509 if (token_to_read == WORD || token_to_read == ASSIGNMENT_WORD)
2511 yylval.word = word_desc_to_read;
2512 word_desc_to_read = (WORD_DESC *)NULL;
2518 #if defined (COND_COMMAND)
2519 if ((parser_state & (PST_CONDCMD|PST_CONDEXPR)) == PST_CONDCMD)
2521 cond_lineno = line_number;
2522 parser_state |= PST_CONDEXPR;
2523 yylval.command = parse_cond_command ();
2524 if (cond_token != COND_END)
2529 token_to_read = COND_END;
2530 parser_state &= ~(PST_CONDEXPR|PST_CONDCMD);
2536 /* This is a place to jump back to once we have successfully expanded a
2537 token with an alias and pushed the string with push_string () */
2541 /* Read a single word from input. Start by skipping blanks. */
2542 while ((character = shell_getc (1)) != EOF && whitespace (character))
2545 if (character == EOF)
2551 if MBTEST(character == '#' && (!interactive || interactive_comments))
2553 /* A comment. Discard until EOL or EOF, and then return a newline. */
2554 discard_until ('\n');
2556 character = '\n'; /* this will take the next if statement and return. */
2559 if (character == '\n')
2561 /* If we're about to return an unquoted newline, we can go and collect
2562 the text of any pending here document. */
2564 gather_here_documents ();
2567 parser_state &= ~PST_ALEXPNEXT;
2573 /* Shell meta-characters. */
2574 if MBTEST(shellmeta (character) && ((parser_state & PST_DBLPAREN) == 0))
2577 /* Turn off alias tokenization iff this character sequence would
2578 not leave us ready to read a command. */
2579 if (character == '<' || character == '>')
2580 parser_state &= ~PST_ALEXPNEXT;
2583 peek_char = shell_getc (1);
2584 if (character == peek_char)
2589 /* If '<' then we could be at "<<" or at "<<-". We have to
2590 look ahead one more character. */
2591 peek_char = shell_getc (1);
2592 if (peek_char == '-')
2593 return (LESS_LESS_MINUS);
2594 else if (peek_char == '<')
2595 return (LESS_LESS_LESS);
2598 shell_ungetc (peek_char);
2603 return (GREATER_GREATER);
2606 parser_state |= PST_CASEPAT;
2608 parser_state &= ~PST_ALEXPNEXT;
2618 #if defined (DPAREN_ARITHMETIC) || defined (ARITH_FOR_COMMAND)
2620 result = parse_dparen (character);
2628 else if MBTEST(character == '<' && peek_char == '&')
2630 else if MBTEST(character == '>' && peek_char == '&')
2631 return (GREATER_AND);
2632 else if MBTEST(character == '<' && peek_char == '>')
2633 return (LESS_GREATER);
2634 else if MBTEST(character == '>' && peek_char == '|')
2635 return (GREATER_BAR);
2636 else if MBTEST(peek_char == '>' && character == '&')
2637 return (AND_GREATER);
2639 shell_ungetc (peek_char);
2641 /* If we look like we are reading the start of a function
2642 definition, then let the reader know about it so that
2643 we will do the right thing with `{'. */
2644 if MBTEST(character == ')' && last_read_token == '(' && token_before_that == WORD)
2646 parser_state |= PST_ALLOWOPNBRC;
2648 parser_state &= ~PST_ALEXPNEXT;
2650 function_dstart = line_number;
2653 /* case pattern lists may be preceded by an optional left paren. If
2654 we're not trying to parse a case pattern list, the left paren
2655 indicates a subshell. */
2656 if MBTEST(character == '(' && (parser_state & PST_CASEPAT) == 0) /* ) */
2657 parser_state |= PST_SUBSHELL;
2659 else if MBTEST((parser_state & PST_CASEPAT) && character == ')')
2660 parser_state &= ~PST_CASEPAT;
2662 else if MBTEST((parser_state & PST_SUBSHELL) && character == ')')
2663 parser_state &= ~PST_SUBSHELL;
2665 #if defined (PROCESS_SUBSTITUTION)
2666 /* Check for the constructs which introduce process substitution.
2667 Shells running in `posix mode' don't do process substitution. */
2668 if MBTEST(posixly_correct || ((character != '>' && character != '<') || peek_char != '(')) /*)*/
2669 #endif /* PROCESS_SUBSTITUTION */
2673 /* Hack <&- (close stdin) case. Also <&N- (dup and close). */
2674 if MBTEST(character == '-' && (last_read_token == LESS_AND || last_read_token == GREATER_AND))
2677 /* Okay, if we got this far, we have to read a word. Read one,
2678 and then check it against the known ones. */
2679 result = read_token_word (character);
2681 if (result == RE_READ_TOKEN)
2688 * Match a $(...) or other grouping construct. This has to handle embedded
2689 * quoted strings ('', ``, "") and nested constructs. It also must handle
2690 * reprompting the user, if necessary, after reading a newline (unless the
2691 * P_NONL flag is passed), and returning correct error values if it reads
2694 #define P_FIRSTCLOSE 0x01
2695 #define P_ALLOWESC 0x02
2696 #define P_DQUOTE 0x04
2698 static char matched_pair_error;
2700 parse_matched_pair (qc, open, close, lenp, flags)
2701 int qc; /* `"' if this construct is within double quotes */
2705 int count, ch, was_dollar;
2706 int pass_next_character, nestlen, ttranslen, start_lineno;
2707 char *ret, *nestret, *ttrans;
2708 int retind, retsize, rflags;
2711 pass_next_character = was_dollar = 0;
2713 /* RFLAGS is the set of flags we want to pass to recursive calls. */
2714 rflags = (qc == '"') ? P_DQUOTE : (flags & P_DQUOTE);
2716 ret = (char *)xmalloc (retsize = 64);
2719 start_lineno = line_number;
2722 ch = shell_getc ((qc != '\'' || (flags & P_ALLOWESC)) && pass_next_character == 0);
2726 parser_error (start_lineno, _("unexpected EOF while looking for matching `%c'"), close);
2727 EOF_Reached = 1; /* XXX */
2728 return (&matched_pair_error);
2731 /* Possible reprompting. */
2732 if (ch == '\n' && SHOULD_PROMPT ())
2735 if (pass_next_character) /* last char was backslash */
2737 pass_next_character = 0;
2738 if (qc != '\'' && ch == '\n') /* double-quoted \<newline> disappears. */
2740 if (retind > 0) retind--; /* swallow previously-added backslash */
2744 RESIZE_MALLOCED_BUFFER (ret, retind, 2, retsize, 64);
2745 if MBTEST(ch == CTLESC || ch == CTLNUL)
2746 ret[retind++] = CTLESC;
2750 else if MBTEST(ch == CTLESC || ch == CTLNUL) /* special shell escapes */
2752 RESIZE_MALLOCED_BUFFER (ret, retind, 2, retsize, 64);
2753 ret[retind++] = CTLESC;
2757 else if MBTEST(ch == close) /* ending delimiter */
2760 /* handle nested ${...} specially. */
2761 else if MBTEST(open != close && was_dollar && open == '{' && ch == open) /* } */
2764 else if MBTEST(((flags & P_FIRSTCLOSE) == 0) && ch == open) /* nested begin */
2767 /* Add this character. */
2768 RESIZE_MALLOCED_BUFFER (ret, retind, 1, retsize, 64);
2771 if (open == '\'') /* '' inside grouping construct */
2773 if MBTEST((flags & P_ALLOWESC) && ch == '\\')
2774 pass_next_character++;
2778 if MBTEST(ch == '\\') /* backslashes */
2779 pass_next_character++;
2781 if (open != close) /* a grouping construct */
2783 if MBTEST(shellquote (ch))
2785 /* '', ``, or "" inside $(...) or other grouping construct. */
2786 push_delimiter (dstack, ch);
2787 if MBTEST(was_dollar && ch == '\'') /* $'...' inside group */
2788 nestret = parse_matched_pair (ch, ch, ch, &nestlen, P_ALLOWESC|rflags);
2790 nestret = parse_matched_pair (ch, ch, ch, &nestlen, rflags);
2791 pop_delimiter (dstack);
2792 if (nestret == &matched_pair_error)
2795 return &matched_pair_error;
2797 if MBTEST(was_dollar && ch == '\'' && (extended_quote || (rflags & P_DQUOTE) == 0))
2799 /* Translate $'...' here. */
2800 ttrans = ansiexpand (nestret, 0, nestlen - 1, &ttranslen);
2802 nestret = sh_single_quote (ttrans);
2804 nestlen = strlen (nestret);
2805 retind -= 2; /* back up before the $' */
2807 else if MBTEST(was_dollar && ch == '"' && (extended_quote || (rflags & P_DQUOTE) == 0))
2809 /* Locale expand $"..." here. */
2810 ttrans = localeexpand (nestret, 0, nestlen - 1, start_lineno, &ttranslen);
2812 nestret = (char *)xmalloc (ttranslen + 3);
2814 strcpy (nestret + 1, ttrans);
2815 nestret[ttranslen + 1] = '"';
2816 nestret[ttranslen += 2] = '\0';
2818 nestlen = ttranslen;
2819 retind -= 2; /* back up before the $" */
2824 RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2825 strcpy (ret + retind, nestret);
2831 /* Parse an old-style command substitution within double quotes as a
2833 /* XXX - sh and ksh93 don't do this - XXX */
2834 else if MBTEST(open == '"' && ch == '`')
2836 nestret = parse_matched_pair (0, '`', '`', &nestlen, rflags);
2837 if (nestret == &matched_pair_error)
2840 return &matched_pair_error;
2844 RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2845 strcpy (ret + retind, nestret);
2850 else if MBTEST(was_dollar && (ch == '(' || ch == '{' || ch == '[')) /* ) } ] */
2851 /* check for $(), $[], or ${} inside quoted string. */
2853 if (open == ch) /* undo previous increment */
2855 if (ch == '(') /* ) */
2856 nestret = parse_matched_pair (0, '(', ')', &nestlen, rflags);
2857 else if (ch == '{') /* } */
2858 nestret = parse_matched_pair (0, '{', '}', &nestlen, P_FIRSTCLOSE|rflags);
2859 else if (ch == '[') /* ] */
2860 nestret = parse_matched_pair (0, '[', ']', &nestlen, rflags);
2861 if (nestret == &matched_pair_error)
2864 return &matched_pair_error;
2868 RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2869 strcpy (ret + retind, nestret);
2874 was_dollar = MBTEST(ch == '$');
2883 #if defined (DPAREN_ARITHMETIC) || defined (ARITH_FOR_COMMAND)
2884 /* Parse a double-paren construct. It can be either an arithmetic
2885 command, an arithmetic `for' command, or a nested subshell. Returns
2886 the parsed token, -1 on error, or -2 if we didn't do anything and
2887 should just go on. */
2892 int cmdtyp, len, sline;
2896 #if defined (ARITH_FOR_COMMAND)
2897 if (last_read_token == FOR)
2899 arith_for_lineno = line_number;
2900 cmdtyp = parse_arith_cmd (&wval, 0);
2903 wd = make_word (wval);
2904 yylval.word_list = make_word_list (wd, (WORD_LIST *)NULL);
2906 return (ARITH_FOR_EXPRS);
2909 return -1; /* ERROR */
2913 #if defined (DPAREN_ARITHMETIC)
2914 if (reserved_word_acceptable (last_read_token))
2916 sline = line_number;
2918 cmdtyp = parse_arith_cmd (&wval, 1);
2920 cmdtyp = parse_arith_cmd (&wval, 0);
2922 if (cmdtyp == 1) /* arithmetic command */
2924 wd = make_word (wval);
2926 wd->flags = W_QUOTED;
2928 wd->flags = W_QUOTED|W_NOSPLIT|W_NOGLOB;
2930 yylval.word_list = make_word_list (wd, (WORD_LIST *)NULL);
2931 free (wval); /* make_word copies it */
2934 else if (cmdtyp == 0) /* nested subshell */
2936 push_string (wval, 0, (alias_t *)NULL);
2937 if ((parser_state & PST_CASEPAT) == 0)
2938 parser_state |= PST_SUBSHELL;
2946 return -2; /* XXX */
2949 /* We've seen a `(('. Look for the matching `))'. If we get it, return 1.
2950 If not, assume it's a nested subshell for backwards compatibility and
2951 return 0. In any case, put the characters we've consumed into a locally-
2952 allocated buffer and make *ep point to that buffer. Return -1 on an
2953 error, for example EOF. */
2955 parse_arith_cmd (ep, adddq)
2959 int exp_lineno, rval, c;
2960 char *ttok, *tokstr;
2963 exp_lineno = line_number;
2964 ttok = parse_matched_pair (0, '(', ')', &ttoklen, 0);
2966 if (ttok == &matched_pair_error)
2968 /* Check that the next character is the closing right paren. If
2969 not, this is a syntax error. ( */
2974 tokstr = (char *)xmalloc (ttoklen + 4);
2976 /* if ADDDQ != 0 then (( ... )) -> "..." */
2977 if (rval == 1 && adddq) /* arith cmd, add double quotes */
2980 strncpy (tokstr + 1, ttok, ttoklen - 1);
2981 tokstr[ttoklen] = '"';
2982 tokstr[ttoklen+1] = '\0';
2984 else if (rval == 1) /* arith cmd, don't add double quotes */
2986 strncpy (tokstr, ttok, ttoklen - 1);
2987 tokstr[ttoklen-1] = '\0';
2989 else /* nested subshell */
2992 strncpy (tokstr + 1, ttok, ttoklen - 1);
2993 tokstr[ttoklen] = ')';
2994 tokstr[ttoklen+1] = c;
2995 tokstr[ttoklen+2] = '\0';
3002 #endif /* DPAREN_ARITHMETIC || ARITH_FOR_COMMAND */
3004 #if defined (COND_COMMAND)
3010 if (EOF_Reached && cond_token != COND_ERROR) /* [[ */
3011 parser_error (cond_lineno, _("unexpected EOF while looking for `]]'"));
3012 else if (cond_token != COND_ERROR)
3014 if (etext = error_token_from_token (cond_token))
3016 parser_error (cond_lineno, _("syntax error in conditional expression: unexpected token `%s'"), etext);
3020 parser_error (cond_lineno, _("syntax error in conditional expression"));
3027 return (cond_or ());
3036 if (cond_token == OR_OR)
3039 l = make_cond_node (COND_OR, (WORD_DESC *)NULL, l, r);
3050 if (cond_token == AND_AND)
3053 l = make_cond_node (COND_AND, (WORD_DESC *)NULL, l, r);
3059 cond_skip_newlines ()
3061 while ((cond_token = read_token (READ)) == '\n')
3063 if (SHOULD_PROMPT ())
3066 return (cond_token);
3069 #define COND_RETURN_ERROR() \
3070 do { cond_token = COND_ERROR; return ((COND_COM *)NULL); } while (0)
3076 COND_COM *term, *tleft, *tright;
3080 /* Read a token. It can be a left paren, a `!', a unary operator, or a
3081 word that should be the first argument of a binary operator. Start by
3082 skipping newlines, since this is a compound command. */
3083 tok = cond_skip_newlines ();
3084 lineno = line_number;
3085 if (tok == COND_END)
3087 COND_RETURN_ERROR ();
3089 else if (tok == '(')
3091 term = cond_expr ();
3092 if (cond_token != ')')
3095 dispose_cond_node (term); /* ( */
3096 if (etext = error_token_from_token (cond_token))
3098 parser_error (lineno, _("unexpected token `%s', expected `)'"), etext);
3102 parser_error (lineno, _("expected `)'"));
3103 COND_RETURN_ERROR ();
3105 term = make_cond_node (COND_EXPR, (WORD_DESC *)NULL, term, (COND_COM *)NULL);
3106 (void)cond_skip_newlines ();
3108 else if (tok == BANG || (tok == WORD && (yylval.word->word[0] == '!' && yylval.word->word[1] == '\0')))
3111 dispose_word (yylval.word); /* not needed */
3112 term = cond_term ();
3114 term->flags |= CMD_INVERT_RETURN;
3116 else if (tok == WORD && test_unop (yylval.word->word))
3119 tok = read_token (READ);
3122 tleft = make_cond_node (COND_TERM, yylval.word, (COND_COM *)NULL, (COND_COM *)NULL);
3123 term = make_cond_node (COND_UNARY, op, tleft, (COND_COM *)NULL);
3128 if (etext = error_token_from_token (tok))
3130 parser_error (line_number, _("unexpected argument `%s' to conditional unary operator"), etext);
3134 parser_error (line_number, _("unexpected argument to conditional unary operator"));
3135 COND_RETURN_ERROR ();
3138 (void)cond_skip_newlines ();
3140 else if (tok == WORD) /* left argument to binary operator */
3143 tleft = make_cond_node (COND_TERM, yylval.word, (COND_COM *)NULL, (COND_COM *)NULL);
3146 tok = read_token (READ);
3147 if (tok == WORD && test_binop (yylval.word->word))
3149 #if defined (COND_REGEXP)
3150 else if (tok == WORD && STREQ (yylval.word->word,"=~"))
3153 else if (tok == '<' || tok == '>')
3154 op = make_word_from_token (tok); /* ( */
3155 /* There should be a check before blindly accepting the `)' that we have
3156 seen the opening `('. */
3157 else if (tok == COND_END || tok == AND_AND || tok == OR_OR || tok == ')')
3159 /* Special case. [[ x ]] is equivalent to [[ -n x ]], just like
3160 the test command. Similarly for [[ x && expr ]] or
3161 [[ x || expr ]] or [[ (x) ]]. */
3162 op = make_word ("-n");
3163 term = make_cond_node (COND_UNARY, op, tleft, (COND_COM *)NULL);
3169 if (etext = error_token_from_token (tok))
3171 parser_error (line_number, _("unexpected token `%s', conditional binary operator expected"), etext);
3175 parser_error (line_number, _("conditional binary operator expected"));
3176 dispose_cond_node (tleft);
3177 COND_RETURN_ERROR ();
3181 tok = read_token (READ);
3184 tright = make_cond_node (COND_TERM, yylval.word, (COND_COM *)NULL, (COND_COM *)NULL);
3185 term = make_cond_node (COND_BINARY, op, tleft, tright);
3189 if (etext = error_token_from_token (tok))
3191 parser_error (line_number, _("unexpected argument `%s' to conditional binary operator"), etext);
3195 parser_error (line_number, _("unexpected argument to conditional binary operator"));
3196 dispose_cond_node (tleft);
3198 COND_RETURN_ERROR ();
3201 (void)cond_skip_newlines ();
3206 parser_error (line_number, _("unexpected token `%c' in conditional command"), tok);
3207 else if (etext = error_token_from_token (tok))
3209 parser_error (line_number, _("unexpected token `%s' in conditional command"), etext);
3213 parser_error (line_number, _("unexpected token %d in conditional command"), tok);
3214 COND_RETURN_ERROR ();
3219 /* This is kind of bogus -- we slip a mini recursive-descent parser in
3220 here to handle the conditional statement syntax. */
3222 parse_cond_command ()
3226 cexp = cond_expr ();
3227 return (make_cond_command (cexp));
3231 #if defined (ARRAY_VARS)
3232 /* When this is called, it's guaranteed that we don't care about anything
3233 in t beyond i. We do save and restore the chars, though. */
3235 token_is_assignment (t, i)
3239 unsigned char c, c1;
3242 c = t[i]; c1 = t[i+1];
3243 t[i] = '='; t[i+1] = '\0';
3244 r = assignment (t, (parser_state & PST_COMPASSIGN) != 0);
3245 t[i] = c; t[i+1] = c1;
3250 token_is_ident (t, i)
3259 r = legal_identifier (t);
3266 read_token_word (character)
3269 /* The value for YYLVAL when a WORD is read. */
3270 WORD_DESC *the_word;
3272 /* Index into the token that we are building. */
3275 /* ALL_DIGITS becomes zero when we see a non-digit. */
3276 int all_digit_token;
3278 /* DOLLAR_PRESENT becomes non-zero if we see a `$'. */
3281 /* QUOTED becomes non-zero if we see one of ("), ('), (`), or (\). */
3284 /* Non-zero means to ignore the value of the next character, and just
3285 to add it no matter what. */
3286 int pass_next_character;
3288 /* The current delimiting character. */
3290 int result, peek_char;
3291 char *ttok, *ttrans;
3292 int ttoklen, ttranslen;
3295 if (token_buffer_size < TOKEN_DEFAULT_INITIAL_SIZE)
3296 token = (char *)xrealloc (token, token_buffer_size = TOKEN_DEFAULT_INITIAL_SIZE);
3299 all_digit_token = DIGIT (character);
3300 dollar_present = quoted = pass_next_character = 0;
3304 if (character == EOF)
3307 if (pass_next_character)
3309 pass_next_character = 0;
3313 cd = current_delimiter (dstack);
3315 /* Handle backslashes. Quote lots of things when not inside of
3316 double-quotes, quote some things inside of double-quotes. */
3317 if MBTEST(character == '\\')
3319 peek_char = shell_getc (0);
3321 /* Backslash-newline is ignored in all cases except
3322 when quoted with single quotes. */
3323 if (peek_char == '\n')
3326 goto next_character;
3330 shell_ungetc (peek_char);
3332 /* If the next character is to be quoted, note it now. */
3333 if (cd == 0 || cd == '`' ||
3334 (cd == '"' && peek_char >= 0 && (sh_syntaxtab[peek_char] & CBSDQUOTE)))
3335 pass_next_character++;
3342 /* Parse a matched pair of quote characters. */
3343 if MBTEST(shellquote (character))
3345 push_delimiter (dstack, character);
3346 ttok = parse_matched_pair (character, character, character, &ttoklen, 0);
3347 pop_delimiter (dstack);
3348 if (ttok == &matched_pair_error)
3349 return -1; /* Bail immediately. */
3350 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
3351 token_buffer_size, TOKEN_DEFAULT_GROW_SIZE);
3352 token[token_index++] = character;
3353 strcpy (token + token_index, ttok);
3354 token_index += ttoklen;
3355 all_digit_token = 0;
3357 dollar_present |= (character == '"' && strchr (ttok, '$') != 0);
3359 goto next_character;
3362 #ifdef EXTENDED_GLOB
3363 /* Parse a ksh-style extended pattern matching specification. */
3364 if (extended_glob && PATTERN_CHAR (character))
3366 peek_char = shell_getc (1);
3367 if MBTEST(peek_char == '(') /* ) */
3369 push_delimiter (dstack, peek_char);
3370 ttok = parse_matched_pair (cd, '(', ')', &ttoklen, 0);
3371 pop_delimiter (dstack);
3372 if (ttok == &matched_pair_error)
3373 return -1; /* Bail immediately. */
3374 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
3376 TOKEN_DEFAULT_GROW_SIZE);
3377 token[token_index++] = character;
3378 token[token_index++] = peek_char;
3379 strcpy (token + token_index, ttok);
3380 token_index += ttoklen;
3382 dollar_present = all_digit_token = 0;
3383 goto next_character;
3386 shell_ungetc (peek_char);
3388 #endif /* EXTENDED_GLOB */
3390 /* If the delimiter character is not single quote, parse some of
3391 the shell expansions that must be read as a single word. */
3392 if (shellexp (character))
3394 peek_char = shell_getc (1);
3395 /* $(...), <(...), >(...), $((...)), ${...}, and $[...] constructs */
3396 if MBTEST(peek_char == '(' || \
3397 ((peek_char == '{' || peek_char == '[') && character == '$')) /* ) ] } */
3399 if (peek_char == '{') /* } */
3400 ttok = parse_matched_pair (cd, '{', '}', &ttoklen, P_FIRSTCLOSE);
3401 else if (peek_char == '(') /* ) */
3403 /* XXX - push and pop the `(' as a delimiter for use by
3404 the command-oriented-history code. This way newlines
3405 appearing in the $(...) string get added to the
3406 history literally rather than causing a possibly-
3407 incorrect `;' to be added. ) */
3408 push_delimiter (dstack, peek_char);
3409 ttok = parse_matched_pair (cd, '(', ')', &ttoklen, 0);
3410 pop_delimiter (dstack);
3413 ttok = parse_matched_pair (cd, '[', ']', &ttoklen, 0);
3414 if (ttok == &matched_pair_error)
3415 return -1; /* Bail immediately. */
3416 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
3418 TOKEN_DEFAULT_GROW_SIZE);
3419 token[token_index++] = character;
3420 token[token_index++] = peek_char;
3421 strcpy (token + token_index, ttok);
3422 token_index += ttoklen;
3425 all_digit_token = 0;
3426 goto next_character;
3428 /* This handles $'...' and $"..." new-style quoted strings. */
3429 else if MBTEST(character == '$' && (peek_char == '\'' || peek_char == '"'))
3433 first_line = line_number;
3434 push_delimiter (dstack, peek_char);
3435 ttok = parse_matched_pair (peek_char, peek_char, peek_char,
3437 (peek_char == '\'') ? P_ALLOWESC : 0);
3438 pop_delimiter (dstack);
3439 if (ttok == &matched_pair_error)
3441 if (peek_char == '\'')
3443 ttrans = ansiexpand (ttok, 0, ttoklen - 1, &ttranslen);
3445 /* Insert the single quotes and correctly quote any
3446 embedded single quotes (allowed because P_ALLOWESC was
3447 passed to parse_matched_pair). */
3448 ttok = sh_single_quote (ttrans);
3451 ttranslen = strlen (ttrans);
3455 /* Try to locale-expand the converted string. */
3456 ttrans = localeexpand (ttok, 0, ttoklen - 1, first_line, &ttranslen);
3459 /* Add the double quotes back */
3460 ttok = (char *)xmalloc (ttranslen + 3);
3462 strcpy (ttok + 1, ttrans);
3463 ttok[ttranslen + 1] = '"';
3464 ttok[ttranslen += 2] = '\0';
3469 RESIZE_MALLOCED_BUFFER (token, token_index, ttranslen + 2,
3471 TOKEN_DEFAULT_GROW_SIZE);
3472 strcpy (token + token_index, ttrans);
3473 token_index += ttranslen;
3476 all_digit_token = 0;
3477 goto next_character;
3479 /* This could eventually be extended to recognize all of the
3480 shell's single-character parameter expansions, and set flags.*/
3481 else if MBTEST(character == '$' && peek_char == '$')
3483 ttok = (char *)xmalloc (3);
3484 ttok[0] = ttok[1] = '$';
3486 RESIZE_MALLOCED_BUFFER (token, token_index, 3,
3488 TOKEN_DEFAULT_GROW_SIZE);
3489 strcpy (token + token_index, ttok);
3492 all_digit_token = 0;
3494 goto next_character;
3497 shell_ungetc (peek_char);
3500 #if defined (ARRAY_VARS)
3501 /* Identify possible array subscript assignment; match [...] */
3502 else if MBTEST(character == '[' && token_index > 0 && assignment_acceptable (last_read_token) && token_is_ident (token, token_index)) /* ] */
3504 ttok = parse_matched_pair (cd, '[', ']', &ttoklen, 0);
3505 if (ttok == &matched_pair_error)
3506 return -1; /* Bail immediately. */
3507 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
3509 TOKEN_DEFAULT_GROW_SIZE);
3510 token[token_index++] = character;
3511 strcpy (token + token_index, ttok);
3512 token_index += ttoklen;
3514 all_digit_token = 0;
3515 goto next_character;
3517 /* Identify possible compound array variable assignment. */
3518 else if MBTEST(character == '=' && token_index > 0 && token_is_assignment (token, token_index))
3520 peek_char = shell_getc (1);
3521 if MBTEST(peek_char == '(') /* ) */
3523 ttok = parse_compound_assignment (&ttoklen);
3525 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 4,
3527 TOKEN_DEFAULT_GROW_SIZE);
3529 token[token_index++] = '=';
3530 token[token_index++] = '(';
3533 strcpy (token + token_index, ttok);
3534 token_index += ttoklen;
3536 token[token_index++] = ')';
3538 all_digit_token = 0;
3539 goto next_character;
3542 shell_ungetc (peek_char);
3546 /* When not parsing a multi-character word construct, shell meta-
3547 characters break words. */
3548 if MBTEST(shellbreak (character))
3550 shell_ungetc (character);
3556 all_digit_token &= DIGIT (character);
3557 dollar_present |= character == '$';
3559 if (character == CTLESC || character == CTLNUL)
3560 token[token_index++] = CTLESC;
3562 token[token_index++] = character;
3564 RESIZE_MALLOCED_BUFFER (token, token_index, 1, token_buffer_size,
3565 TOKEN_DEFAULT_GROW_SIZE);
3568 if (character == '\n' && SHOULD_PROMPT ())
3571 /* We want to remove quoted newlines (that is, a \<newline> pair)
3572 unless we are within single quotes or pass_next_character is
3573 set (the shell equivalent of literal-next). */
3574 cd = current_delimiter (dstack);
3575 character = shell_getc (cd != '\'' && pass_next_character == 0);
3576 } /* end for (;;) */
3580 token[token_index] = '\0';
3582 /* Check to see what thing we should return. If the last_read_token
3583 is a `<', or a `&', or the character which ended this token is
3584 a '>' or '<', then, and ONLY then, is this input token a NUMBER.
3585 Otherwise, it is just a word, and should be returned as such. */
3586 if MBTEST(all_digit_token && (character == '<' || character == '>' || \
3587 last_read_token == LESS_AND || \
3588 last_read_token == GREATER_AND))
3590 if (legal_number (token, &lvalue) && (int)lvalue == lvalue)
3591 yylval.number = lvalue;
3597 /* Check for special case tokens. */
3598 result = (last_shell_getc_is_singlebyte) ? special_case_tokens (token) : -1;
3603 /* Posix.2 does not allow reserved words to be aliased, so check for all
3604 of them, including special cases, before expanding the current token
3606 if MBTEST(posixly_correct)
3607 CHECK_FOR_RESERVED_WORD (token);
3609 /* Aliases are expanded iff EXPAND_ALIASES is non-zero, and quoting
3610 inhibits alias expansion. */
3611 if (expand_aliases && quoted == 0)
3613 result = alias_expand_token (token);
3614 if (result == RE_READ_TOKEN)
3615 return (RE_READ_TOKEN);
3616 else if (result == NO_EXPANSION)
3617 parser_state &= ~PST_ALEXPNEXT;
3620 /* If not in Posix.2 mode, check for reserved words after alias
3622 if MBTEST(posixly_correct == 0)
3624 CHECK_FOR_RESERVED_WORD (token);
3626 the_word = (WORD_DESC *)xmalloc (sizeof (WORD_DESC));
3627 the_word->word = (char *)xmalloc (1 + token_index);
3628 the_word->flags = 0;
3629 strcpy (the_word->word, token);
3631 the_word->flags |= W_HASDOLLAR;
3633 the_word->flags |= W_QUOTED;
3634 /* A word is an assignment if it appears at the beginning of a
3635 simple command, or after another assignment word. This is
3636 context-dependent, so it cannot be handled in the grammar. */
3637 if (assignment (token, (parser_state & PST_COMPASSIGN) != 0))
3639 the_word->flags |= W_ASSIGNMENT;
3640 /* Don't perform word splitting on assignment statements. */
3641 if (assignment_acceptable (last_read_token) || (parser_state & PST_COMPASSIGN) != 0)
3642 the_word->flags |= W_NOSPLIT;
3645 yylval.word = the_word;
3647 result = ((the_word->flags & (W_ASSIGNMENT|W_NOSPLIT)) == (W_ASSIGNMENT|W_NOSPLIT))
3648 ? ASSIGNMENT_WORD : WORD;
3650 switch (last_read_token)
3653 parser_state |= PST_ALLOWOPNBRC;
3654 function_dstart = line_number;
3659 if (word_top < MAX_CASE_NEST)
3661 word_lineno[word_top] = line_number;
3668 /* Return 1 if TOKSYM is a token that after being read would allow
3669 a reserved word to be seen, else 0. */
3671 reserved_word_acceptable (toksym)
3707 /* Return the index of TOKEN in the alist of reserved words, or -1 if
3708 TOKEN is not a shell reserved word. */
3710 find_reserved_word (tokstr)
3714 for (i = 0; word_token_alist[i].word; i++)
3715 if (STREQ (tokstr, word_token_alist[i].word))
3721 #if defined (READLINE)
3722 /* Called after each time readline is called. This insures that whatever
3723 the new prompt string is gets propagated to readline's local prompt
3726 reset_readline_prompt ()
3730 if (prompt_string_pointer)
3732 temp_prompt = (*prompt_string_pointer)
3733 ? decode_prompt_string (*prompt_string_pointer)
3736 if (temp_prompt == 0)
3738 temp_prompt = (char *)xmalloc (1);
3739 temp_prompt[0] = '\0';
3742 FREE (current_readline_prompt);
3743 current_readline_prompt = temp_prompt;
3746 #endif /* READLINE */
3749 #if defined (HISTORY)
3750 /* A list of tokens which can be followed by newlines, but not by
3751 semi-colons. When concatenating multiple lines of history, the
3752 newline separator for such tokens is replaced with a space. */
3753 static int no_semi_successors[] = {
3754 '\n', '{', '(', ')', ';', '&', '|',
3755 CASE, DO, ELSE, IF, SEMI_SEMI, THEN, UNTIL, WHILE, AND_AND, OR_OR, IN,
3759 /* If we are not within a delimited expression, try to be smart
3760 about which separators can be semi-colons and which must be
3761 newlines. Returns the string that should be added into the
3764 history_delimiting_chars ()
3768 if (dstack.delimiter_depth != 0)
3771 /* First, handle some special cases. */
3773 /* If we just read `()', assume it's a function definition, and don't
3774 add a semicolon. If the token before the `)' was not `(', and we're
3775 not in the midst of parsing a case statement, assume it's a
3776 parenthesized command and add the semicolon. */
3778 if (token_before_that == ')')
3780 if (two_tokens_ago == '(') /*)*/ /* function def */
3782 /* This does not work for subshells inside case statement
3783 command lists. It's a suboptimal solution. */
3784 else if (parser_state & PST_CASESTMT) /* case statement pattern */
3787 return "; "; /* (...) subshell */
3789 else if (token_before_that == WORD && two_tokens_ago == FUNCTION)
3790 return " "; /* function def using `function name' without `()' */
3792 else if (token_before_that == WORD && two_tokens_ago == FOR)
3794 /* Tricky. `for i\nin ...' should not have a semicolon, but
3795 `for i\ndo ...' should. We do what we can. */
3796 for (i = shell_input_line_index; whitespace(shell_input_line[i]); i++)
3798 if (shell_input_line[i] && shell_input_line[i] == 'i' && shell_input_line[i+1] == 'n')
3803 for (i = 0; no_semi_successors[i]; i++)
3805 if (token_before_that == no_semi_successors[i])
3811 #endif /* HISTORY */
3813 /* Issue a prompt, or prepare to issue a prompt when the next character
3820 if (interactive == 0 || expanding_alias()) /* XXX */
3823 ps1_prompt = get_string_value ("PS1");
3824 ps2_prompt = get_string_value ("PS2");
3826 if (!prompt_string_pointer)
3827 prompt_string_pointer = &ps1_prompt;
3829 temp_prompt = *prompt_string_pointer
3830 ? decode_prompt_string (*prompt_string_pointer)
3833 if (temp_prompt == 0)
3835 temp_prompt = (char *)xmalloc (1);
3836 temp_prompt[0] = '\0';
3839 current_prompt_string = *prompt_string_pointer;
3840 prompt_string_pointer = &ps2_prompt;
3842 #if defined (READLINE)
3843 if (!no_line_editing)
3845 FREE (current_readline_prompt);
3846 current_readline_prompt = temp_prompt;
3849 #endif /* READLINE */
3851 FREE (current_decoded_prompt);
3852 current_decoded_prompt = temp_prompt;
3857 get_current_prompt_level ()
3859 return ((current_prompt_string && current_prompt_string == ps2_prompt) ? 2 : 1);
3863 set_current_prompt_level (x)
3866 prompt_string_pointer = (x == 2) ? &ps2_prompt : &ps1_prompt;
3867 current_prompt_string = *prompt_string_pointer;
3873 fprintf (stderr, "%s", current_decoded_prompt);
3877 /* Return a string which will be printed as a prompt. The string
3878 may contain special characters which are decoded as follows:
3881 \d the date in Day Mon Date format
3882 \e escape (ascii 033)
3883 \h the hostname up to the first `.'
3885 \j the number of active jobs
3886 \l the basename of the shell's tty device name
3889 \s the name of the shell
3890 \t the time in 24-hour hh:mm:ss format
3891 \T the time in 12-hour hh:mm:ss format
3892 \@ the time in 12-hour hh:mm am/pm format
3893 \A the time in 24-hour hh:mm format
3894 \D{fmt} the result of passing FMT to strftime(3)
3896 \v the version of bash (e.g., 2.00)
3897 \V the release of bash, version + patchlevel (e.g., 2.00.0)
3898 \w the current working directory
3899 \W the last element of $PWD
3900 \! the history number of this command
3901 \# the command number of this command
3902 \$ a $ or a # if you are root
3903 \nnn character code nnn in octal
3905 \[ begin a sequence of non-printing chars
3906 \] end a sequence of non-printing chars
3908 #define PROMPT_GROWTH 48
3910 decode_prompt_string (string)
3915 struct dstack save_dstack;
3916 int last_exit_value;
3917 #if defined (PROMPT_STRING_DECODE)
3918 int result_size, result_index;
3920 char *temp, octal_string[4];
3926 result = (char *)xmalloc (result_size = PROMPT_GROWTH);
3927 result[result_index = 0] = 0;
3928 temp = (char *)NULL;
3930 while (c = *string++)
3932 if (posixly_correct && c == '!')
3936 temp = savestring ("!");
3941 #if !defined (HISTORY)
3942 temp = savestring ("1");
3944 temp = itos (history_number ());
3945 #endif /* HISTORY */
3946 string--; /* add_string increments string again. */
3964 strncpy (octal_string, string, 3);
3965 octal_string[3] = '\0';
3967 n = read_octal (octal_string);
3968 temp = (char *)xmalloc (3);
3970 if (n == CTLESC || n == CTLNUL)
3987 for (c = 0; n != -1 && c < 3 && ISOCTAL (*string); c++)
3990 c = 0; /* tested at add_string: */
3998 /* Make the current time/date into a string. */
3999 (void) time (&the_time);
4000 tm = localtime (&the_time);
4003 n = strftime (timebuf, sizeof (timebuf), "%a %b %d", tm);
4005 n = strftime (timebuf, sizeof (timebuf), "%H:%M:%S", tm);
4007 n = strftime (timebuf, sizeof (timebuf), "%I:%M:%S", tm);
4009 n = strftime (timebuf, sizeof (timebuf), "%I:%M %p", tm);
4011 n = strftime (timebuf, sizeof (timebuf), "%H:%M", tm);
4016 timebuf[sizeof(timebuf) - 1] = '\0';
4018 temp = savestring (timebuf);
4021 case 'D': /* strftime format */
4022 if (string[1] != '{') /* } */
4025 (void) time (&the_time);
4026 tm = localtime (&the_time);
4027 string += 2; /* skip { */
4028 timefmt = xmalloc (strlen (string) + 3);
4029 for (t = timefmt; *string && *string != '}'; )
4032 c = *string; /* tested at add_string */
4033 if (timefmt[0] == '\0')
4036 timefmt[1] = 'X'; /* locale-specific current time */
4039 n = strftime (timebuf, sizeof (timebuf), timefmt, tm);
4045 timebuf[sizeof(timebuf) - 1] = '\0';
4047 if (promptvars || posixly_correct)
4048 /* Make sure that expand_prompt_string is called with a
4049 second argument of Q_DOUBLE_QUOTES if we use this
4051 temp = sh_backslash_quote_for_double_quotes (timebuf);
4053 temp = savestring (timebuf);
4057 temp = (char *)xmalloc (3);
4058 temp[0] = no_line_editing ? '\n' : '\r';
4059 temp[1] = no_line_editing ? '\0' : '\n';
4064 temp = base_pathname (shell_name);
4065 temp = savestring (temp);
4070 temp = (char *)xmalloc (16);
4072 strcpy (temp, dist_version);
4074 sprintf (temp, "%s.%d", dist_version, patch_level);
4080 /* Use the value of PWD because it is much more efficient. */
4081 char t_string[PATH_MAX], *t;
4084 temp = get_string_value ("PWD");
4088 if (getcwd (t_string, sizeof(t_string)) == 0)
4094 tlen = strlen (t_string);
4098 tlen = sizeof (t_string) - 1;
4099 strncpy (t_string, temp, tlen);
4101 t_string[tlen] = '\0';
4103 #define ROOT_PATH(x) ((x)[0] == '/' && (x)[1] == 0)
4104 #define DOUBLE_SLASH_ROOT(x) ((x)[0] == '/' && (x)[1] == '/' && (x)[2] == 0)
4105 /* Abbreviate \W as ~ if $PWD == $HOME */
4106 if (c == 'W' && (((t = get_string_value ("HOME")) == 0) || STREQ (t, temp) == 0))
4108 if (ROOT_PATH (t_string) == 0 && DOUBLE_SLASH_ROOT (t_string) == 0)
4110 t = strrchr (t_string, '/');
4112 strcpy (t_string, t + 1);
4116 #undef DOUBLE_SLASH_ROOT
4118 /* polite_directory_format is guaranteed to return a string
4119 no longer than PATH_MAX - 1 characters. */
4120 strcpy (t_string, polite_directory_format (t_string));
4122 /* If we're going to be expanding the prompt string later,
4123 quote the directory name. */
4124 if (promptvars || posixly_correct)
4125 /* Make sure that expand_prompt_string is called with a
4126 second argument of Q_DOUBLE_QUOTES if we use this
4128 temp = sh_backslash_quote_for_double_quotes (t_string);
4130 temp = savestring (t_string);
4136 if (current_user.user_name == 0)
4137 get_current_user_info ();
4138 temp = savestring (current_user.user_name);
4143 temp = savestring (current_host_name);
4144 if (c == 'h' && (t = (char *)strchr (temp, '.')))
4149 temp = itos (current_command_number);
4153 #if !defined (HISTORY)
4154 temp = savestring ("1");
4156 temp = itos (history_number ());
4157 #endif /* HISTORY */
4161 t = temp = (char *)xmalloc (3);
4162 if ((promptvars || posixly_correct) && (current_user.euid != 0))
4164 *t++ = current_user.euid == 0 ? '#' : '$';
4169 temp = itos (count_all_jobs ());
4173 #if defined (HAVE_TTYNAME)
4174 temp = (char *)ttyname (fileno (stdin));
4175 t = temp ? base_pathname (temp) : "tty";
4176 temp = savestring (t);
4178 temp = savestring ("tty");
4179 #endif /* !HAVE_TTYNAME */
4182 #if defined (READLINE)
4185 if (no_line_editing)
4190 temp = (char *)xmalloc (3);
4192 temp[1] = (c == '[') ? RL_PROMPT_START_IGNORE : RL_PROMPT_END_IGNORE;
4195 #endif /* READLINE */
4201 temp = (char *)xmalloc (2);
4208 else /* (c == '\\') */
4215 temp = (char *)xmalloc (3);
4224 sub_append_string (temp, result, &result_index, &result_size);
4225 temp = (char *)NULL; /* Freed in sub_append_string (). */
4226 result[result_index] = '\0';
4232 RESIZE_MALLOCED_BUFFER (result, result_index, 3, result_size, PROMPT_GROWTH);
4233 result[result_index++] = c;
4234 result[result_index] = '\0';
4237 #else /* !PROMPT_STRING_DECODE */
4238 result = savestring (string);
4239 #endif /* !PROMPT_STRING_DECODE */
4241 /* Save the delimiter stack and point `dstack' to temp space so any
4242 command substitutions in the prompt string won't result in screwing
4243 up the parser's quoting state. */
4244 save_dstack = dstack;
4245 dstack = temp_dstack;
4246 dstack.delimiter_depth = 0;
4248 /* Perform variable and parameter expansion and command substitution on
4249 the prompt string. */
4250 if (promptvars || posixly_correct)
4252 last_exit_value = last_command_exit_value;
4253 list = expand_prompt_string (result, Q_DOUBLE_QUOTES);
4255 result = string_list (list);
4256 dispose_words (list);
4257 last_command_exit_value = last_exit_value;
4261 t = dequote_string (result);
4266 dstack = save_dstack;
4271 /************************************************
4275 ************************************************/
4277 /* Report a syntax error, and restart the parser. Call here for fatal
4283 report_syntax_error ((char *)NULL);
4289 error_token_from_token (token)
4294 if (t = find_token_in_alist (token, word_token_alist, 0))
4297 if (t = find_token_in_alist (token, other_token_alist, 0))
4301 /* This stuff is dicy and needs closer inspection */
4302 switch (current_token)
4305 case ASSIGNMENT_WORD:
4307 t = savestring (yylval.word->word);
4310 t = itos (yylval.number);
4313 if (yylval.word_list)
4314 t = string_list (yylval.word_list);
4316 case ARITH_FOR_EXPRS:
4317 if (yylval.word_list)
4318 t = string_list_internal (yylval.word_list, " ; ");
4321 t = (char *)NULL; /* punt */
4329 error_token_from_text ()
4334 t = shell_input_line;
4335 i = shell_input_line_index;
4339 if (i && t[i] == '\0')
4342 while (i && (whitespace (t[i]) || t[i] == '\n'))
4348 while (i && (member (t[i], " \n\t;|&") == 0))
4351 while (i != token_end && (whitespace (t[i]) || t[i] == '\n'))
4354 /* Return our idea of the offending token. */
4355 if (token_end || (i == 0 && token_end == 0))
4358 msg = substring (t, i, token_end);
4359 else /* one-character token */
4361 msg = (char *)xmalloc (2);
4371 print_offending_line ()
4376 msg = savestring (shell_input_line);
4377 token_end = strlen (msg);
4378 while (token_end && msg[token_end - 1] == '\n')
4379 msg[--token_end] = '\0';
4381 parser_error (line_number, "`%s'", msg);
4385 /* Report a syntax error with line numbers, etc.
4386 Call here for recoverable errors. If you have a message to print,
4387 then place it in MESSAGE, otherwise pass NULL and this will figure
4388 out an appropriate message for you. */
4390 report_syntax_error (message)
4397 parser_error (line_number, "%s", message);
4398 if (interactive && EOF_Reached)
4400 last_command_exit_value = EX_USAGE;
4404 /* If the line of input we're reading is not null, try to find the
4405 objectionable token. First, try to figure out what token the
4406 parser's complaining about by looking at current_token. */
4407 if (current_token != 0 && EOF_Reached == 0 && (msg = error_token_from_token (current_token)))
4409 parser_error (line_number, _("syntax error near unexpected token `%s'"), msg);
4412 if (interactive == 0)
4413 print_offending_line ();
4415 last_command_exit_value = EX_USAGE;
4419 /* If looking at the current token doesn't prove fruitful, try to find the
4420 offending token by analyzing the text of the input line near the current
4421 input line index and report what we find. */
4422 if (shell_input_line && *shell_input_line)
4424 msg = error_token_from_text ();
4427 parser_error (line_number, _("syntax error near `%s'"), msg);
4431 /* If not interactive, print the line containing the error. */
4432 if (interactive == 0)
4433 print_offending_line ();
4437 msg = EOF_Reached ? _("syntax error: unexpected end of file") : _("syntax error");
4438 parser_error (line_number, "%s", msg);
4439 /* When the shell is interactive, this file uses EOF_Reached
4440 only for error reporting. Other mechanisms are used to
4441 decide whether or not to exit. */
4442 if (interactive && EOF_Reached)
4446 last_command_exit_value = EX_USAGE;
4449 /* ??? Needed function. ??? We have to be able to discard the constructs
4450 created during parsing. In the case of error, we want to return
4451 allocated objects to the memory pool. In the case of no error, we want
4452 to throw away the information about where the allocated objects live.
4453 (dispose_command () will actually free the command.) */
4455 discard_parser_constructs (error_p)
4460 /************************************************
4464 ************************************************/
4466 /* Do that silly `type "bye" to exit' stuff. You know, "ignoreeof". */
4468 /* A flag denoting whether or not ignoreeof is set. */
4471 /* The number of times that we have encountered an EOF character without
4472 another character intervening. When this gets above the limit, the
4473 shell terminates. */
4474 int eof_encountered = 0;
4476 /* The limit for eof_encountered. */
4477 int eof_encountered_limit = 10;
4479 /* If we have EOF as the only input unit, this user wants to leave
4480 the shell. If the shell is not interactive, then just leave.
4481 Otherwise, if ignoreeof is set, and we haven't done this the
4482 required number of times in a row, print a message. */
4484 handle_eof_input_unit ()
4488 /* shell.c may use this to decide whether or not to write out the
4489 history, among other things. We use it only for error reporting
4494 /* If the user wants to "ignore" eof, then let her do so, kind of. */
4497 if (eof_encountered < eof_encountered_limit)
4499 fprintf (stderr, _("Use \"%s\" to leave the shell.\n"),
4500 login_shell ? "logout" : "exit");
4502 /* Reset the parsing state. */
4503 last_read_token = current_token = '\n';
4504 /* Reset the prompt string to be $PS1. */
4505 prompt_string_pointer = (char **)NULL;
4511 /* In this case EOF should exit the shell. Do it now. */
4513 exit_builtin ((WORD_LIST *)NULL);
4517 /* We don't write history files, etc., for non-interactive shells. */
4522 /************************************************
4524 * STRING PARSING FUNCTIONS *
4526 ************************************************/
4528 /* It's very important that these two functions treat the characters
4529 between ( and ) identically. */
4531 static WORD_LIST parse_string_error;
4533 /* Take a string and run it through the shell parser, returning the
4534 resultant word list. Used by compound array assignment. */
4536 parse_string_to_word_list (s, flags, whom)
4542 int tok, orig_current_token, orig_line_number, orig_input_terminator;
4543 int orig_line_count;
4544 int old_echo_input, old_expand_aliases;
4545 #if defined (HISTORY)
4546 int old_remember_on_history, old_history_expansion_inhibited;
4549 #if defined (HISTORY)
4550 old_remember_on_history = remember_on_history;
4551 # if defined (BANG_HISTORY)
4552 old_history_expansion_inhibited = history_expansion_inhibited;
4554 bash_history_disable ();
4557 orig_line_number = line_number;
4558 orig_line_count = current_command_line_count;
4559 orig_input_terminator = shell_input_line_terminator;
4560 old_echo_input = echo_input_at_read;
4561 old_expand_aliases = expand_aliases;
4564 last_read_token = WORD; /* WORD to allow reserved words here */
4565 current_command_line_count = 0;
4566 echo_input_at_read = expand_aliases = 0;
4568 with_input_from_string (s, whom);
4569 wl = (WORD_LIST *)NULL;
4572 parser_state |= PST_COMPASSIGN;
4574 while ((tok = read_token (READ)) != yacc_EOF)
4576 if (tok == '\n' && *bash_input.location.string == '\0')
4578 if (tok == '\n') /* Allow newlines in compound assignments */
4580 if (tok != WORD && tok != ASSIGNMENT_WORD)
4582 line_number = orig_line_number + line_number - 1;
4583 orig_current_token = current_token;
4584 current_token = tok;
4585 yyerror ((char *)NULL); /* does the right thing */
4586 current_token = orig_current_token;
4589 wl = &parse_string_error;
4592 wl = make_word_list (yylval.word, wl);
4595 last_read_token = '\n';
4598 #if defined (HISTORY)
4599 remember_on_history = old_remember_on_history;
4600 # if defined (BANG_HISTORY)
4601 history_expansion_inhibited = old_history_expansion_inhibited;
4602 # endif /* BANG_HISTORY */
4603 #endif /* HISTORY */
4605 echo_input_at_read = old_echo_input;
4606 expand_aliases = old_expand_aliases;
4608 current_command_line_count = orig_line_count;
4609 shell_input_line_terminator = orig_input_terminator;
4612 parser_state &= ~PST_COMPASSIGN;
4614 if (wl == &parse_string_error)
4616 last_command_exit_value = EXECUTION_FAILURE;
4617 if (interactive_shell == 0 && posixly_correct)
4618 jump_to_top_level (FORCE_EOF);
4620 jump_to_top_level (DISCARD);
4623 return (REVERSE_LIST (wl, WORD_LIST *));
4627 parse_compound_assignment (retlenp)
4631 int tok, orig_line_number, orig_token_size;
4632 char *saved_token, *ret;
4634 saved_token = token;
4635 orig_token_size = token_buffer_size;
4636 orig_line_number = line_number;
4638 last_read_token = WORD; /* WORD to allow reserved words here */
4640 token = (char *)NULL;
4641 token_buffer_size = 0;
4643 wl = (WORD_LIST *)NULL; /* ( */
4644 parser_state |= PST_COMPASSIGN;
4646 while ((tok = read_token (READ)) != ')')
4648 if (tok == '\n') /* Allow newlines in compound assignments */
4650 if (SHOULD_PROMPT ())
4654 if (tok != WORD && tok != ASSIGNMENT_WORD)
4656 current_token = tok; /* for error reporting */
4657 if (tok == yacc_EOF) /* ( */
4658 parser_error (orig_line_number, _("unexpected EOF while looking for matching `)'"));
4660 yyerror ((char *)NULL); /* does the right thing */
4663 wl = &parse_string_error;
4666 wl = make_word_list (yylval.word, wl);
4670 token = saved_token;
4671 token_buffer_size = orig_token_size;
4673 parser_state &= ~PST_COMPASSIGN;
4675 if (wl == &parse_string_error)
4677 last_command_exit_value = EXECUTION_FAILURE;
4678 last_read_token = '\n'; /* XXX */
4679 if (interactive_shell == 0 && posixly_correct)
4680 jump_to_top_level (FORCE_EOF);
4682 jump_to_top_level (DISCARD);
4685 last_read_token = WORD;
4688 rl = REVERSE_LIST (wl, WORD_LIST *);
4689 ret = string_list (rl);
4696 *retlenp = (ret && *ret) ? strlen (ret) : 0;
4700 /************************************************
4702 * SAVING AND RESTORING PARTIAL PARSE STATE *
4704 ************************************************/
4707 save_parser_state (ps)
4708 sh_parser_state_t *ps;
4710 #if defined (ARRAY_VARS)
4715 ps = xmalloc (sizeof (sh_parser_state_t));
4717 return ((sh_parser_state_t *)NULL);
4719 ps->parser_state = parser_state;
4720 ps->token_state = save_token_state ();
4722 ps->input_line_terminator = shell_input_line_terminator;
4723 ps->eof_encountered = eof_encountered;
4725 ps->current_command_line_count = current_command_line_count;
4727 #if defined (HISTORY)
4728 ps->remember_on_history = remember_on_history;
4729 # if defined (BANG_HISTORY)
4730 ps->history_expansion_inhibited = history_expansion_inhibited;
4734 ps->last_command_exit_value = last_command_exit_value;
4735 #if defined (ARRAY_VARS)
4736 v = find_variable ("PIPESTATUS");
4737 if (v && array_p (v) && array_cell (v))
4738 ps->pipestatus = array_copy (array_cell (v));
4740 ps->pipestatus = (ARRAY *)NULL;
4743 ps->last_shell_builtin = last_shell_builtin;
4744 ps->this_shell_builtin = this_shell_builtin;
4746 ps->expand_aliases = expand_aliases;
4747 ps->echo_input_at_read = echo_input_at_read;
4753 restore_parser_state (ps)
4754 sh_parser_state_t *ps;
4756 #if defined (ARRAY_VARS)
4763 parser_state = ps->parser_state;
4764 if (ps->token_state)
4766 restore_token_state (ps->token_state);
4767 free (ps->token_state);
4770 shell_input_line_terminator = ps->input_line_terminator;
4771 eof_encountered = ps->eof_encountered;
4773 current_command_line_count = ps->current_command_line_count;
4775 #if defined (HISTORY)
4776 remember_on_history = ps->remember_on_history;
4777 # if defined (BANG_HISTORY)
4778 history_expansion_inhibited = ps->history_expansion_inhibited;
4782 last_command_exit_value = ps->last_command_exit_value;
4783 #if defined (ARRAY_VARS)
4784 v = find_variable ("PIPESTATUS");
4785 if (v && array_p (v) && array_cell (v))
4787 array_dispose (array_cell (v));
4788 var_setarray (v, ps->pipestatus);
4792 last_shell_builtin = ps->last_shell_builtin;
4793 this_shell_builtin = ps->this_shell_builtin;
4795 expand_aliases = ps->expand_aliases;
4796 echo_input_at_read = ps->echo_input_at_read;
4799 /************************************************
4801 * MULTIBYTE CHARACTER HANDLING *
4803 ************************************************/
4805 #if defined (HANDLE_MULTIBYTE)
4809 int i, previ, len, c;
4810 mbstate_t mbs, prevs;
4813 if (shell_input_line == NULL)
4815 len = strlen (shell_input_line); /* XXX - shell_input_line_len ? */
4816 FREE (shell_input_line_property);
4817 shell_input_line_property = (char *)xmalloc (len + 1);
4819 memset (&prevs, '\0', sizeof (mbstate_t));
4820 for (i = previ = 0; i < len; i++)
4824 c = shell_input_line[i];
4828 for (j = i; j < len; j++)
4829 shell_input_line_property[j] = 1;
4833 mbclen = mbrlen (shell_input_line + previ, i - previ + 1, &mbs);
4834 if (mbclen == 1 || mbclen == (size_t)-1)
4839 else if (mbclen == (size_t)-2)
4841 else if (mbclen > 1)
4849 /* XXX - what to do if mbrlen returns 0? (null wide character) */
4851 for (j = i; j < len; j++)
4852 shell_input_line_property[j] = 1;
4856 shell_input_line_property[i] = mbclen;
4859 #endif /* HANDLE_MULTIBYTE */