1 /* Yacc grammar for bash. */
3 /* Copyright (C) 1989 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 1, 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, 675 Mass Ave, Cambridge, MA 02139, USA. */
24 #include "bashtypes.h"
27 #if defined (HAVE_UNISTD_H)
31 #if defined (HAVE_LOCALE_H)
44 #include "mailcheck.h"
45 #include "builtins/common.h"
46 #include "builtins/builtext.h"
48 #if defined (READLINE)
49 # include "bashline.h"
50 # include <readline/readline.h>
54 # include "bashhist.h"
55 # include <readline/history.h>
58 #if defined (JOB_CONTROL)
60 #endif /* JOB_CONTROL */
66 #if defined (PROMPT_STRING_DECODE)
67 #include <sys/param.h>
70 #endif /* PROMPT_STRING_DECODE */
72 #define RE_READ_TOKEN -99
73 #define NO_EXPANSION -100
77 extern int eof_encountered;
78 extern int no_line_editing, running_under_emacs;
79 extern int current_command_number;
80 extern int interactive, interactive_shell, login_shell;
81 extern int sourcelevel;
82 extern int posixly_correct;
83 extern int last_command_exit_value;
84 extern int interrupt_immediately;
85 extern char *shell_name, *current_host_name;
86 extern char *dist_version;
87 extern int patch_level;
88 extern int dump_translatable_strings;
89 extern Function *last_shell_builtin, *this_shell_builtin;
90 #if defined (BUFFERED_INPUT)
91 extern int bash_input_fd_changed;
94 /* **************************************************************** */
96 /* "Forward" declarations */
98 /* **************************************************************** */
100 static char *ansiexpand ();
101 static char *localeexpand ();
102 static int reserved_word_acceptable ();
103 static int read_token ();
105 static int parse_arith_cmd ();
106 static int read_token_word ();
107 static void discard_parser_constructs ();
109 static void report_syntax_error ();
110 static void handle_eof_input_unit ();
111 static void prompt_again ();
113 static void reset_readline_prompt ();
115 static void print_prompt ();
117 extern int yyerror ();
119 /* Default prompt strings */
120 char *primary_prompt = PPROMPT;
121 char *secondary_prompt = SPROMPT;
123 /* PROMPT_STRING_POINTER points to one of these, never to an actual string. */
124 char *ps1_prompt, *ps2_prompt;
126 /* Handle on the current prompt string. Indirectly points through
127 ps1_ or ps2_prompt. */
128 char **prompt_string_pointer = (char **)NULL;
129 char *current_prompt_string;
131 /* Non-zero means we expand aliases in commands. */
132 int expand_aliases = 0;
134 /* If non-zero, the decoded prompt string undergoes parameter and
135 variable substitution, command substitution, arithmetic substitution,
136 string expansion, process substitution, and quote removal in
137 decode_prompt_string. */
140 /* The decoded prompt string. Used if READLINE is not defined or if
141 editing is turned off. Analogous to current_readline_prompt. */
142 static char *current_decoded_prompt;
144 /* The number of lines read from input while creating the current command. */
145 int current_command_line_count;
147 /* Variables to manage the task of reading here documents, because we need to
148 defer the reading until after a complete command has been collected. */
149 static REDIRECT *redir_stack[10];
152 /* Where shell input comes from. History expansion is performed on each
153 line when the shell is interactive. */
154 static char *shell_input_line = (char *)NULL;
155 static int shell_input_line_index;
156 static int shell_input_line_size; /* Amount allocated for shell_input_line. */
157 static int shell_input_line_len; /* strlen (shell_input_line) */
159 /* Either zero or EOF. */
160 static int shell_input_line_terminator;
162 /* The line number in a script on which a function definition starts. */
163 static int function_dstart;
165 /* The line number in a script on which a function body starts. */
166 static int function_bstart;
168 static REDIRECTEE redir;
172 WORD_DESC *word; /* the word that we read. */
173 int number; /* the number that we read. */
174 WORD_LIST *word_list;
178 PATTERN_LIST *pattern;
181 /* Reserved words. Members of the first group are only recognized
182 in the case that they are preceded by a list_terminator. Members
183 of the second group are recognized only under special circumstances. */
184 %token IF THEN ELSE ELIF FI CASE ESAC FOR SELECT WHILE UNTIL DO DONE FUNCTION
185 %token IN BANG TIME TIMEOPT
187 /* More general tokens. yylex () knows how to make these. */
188 %token <word> WORD ASSIGNMENT_WORD
189 %token <number> NUMBER
190 %token AND_AND OR_OR GREATER_GREATER LESS_LESS LESS_AND
191 %token GREATER_AND SEMI_SEMI LESS_LESS_MINUS AND_GREATER LESS_GREATER
194 /* The types that the various syntactical units return. */
196 %type <command> inputunit command pipeline pipeline_command
197 %type <command> list list0 list1 compound_list simple_list simple_list1
198 %type <command> simple_command shell_command
199 %type <command> for_command select_command case_command group_command
200 %type <command> function_def if_command elif_clause subshell
201 %type <redirect> redirection redirection_list
202 %type <element> simple_command_element
203 %type <word_list> word_list pattern
204 %type <pattern> pattern_list case_clause_sequence case_clause
205 %type <number> timespec
209 %left '&' ';' '\n' yacc_EOF
214 inputunit: simple_list '\n'
216 /* Case of regular command. Discard the error
217 safety net,and return the command just parsed. */
220 discard_parser_constructs (0);
225 /* Case of regular command, but not a very
226 interesting one. Return a NULL command. */
227 global_command = (COMMAND *)NULL;
232 /* Error during parsing. Return NULL command. */
233 global_command = (COMMAND *)NULL;
235 discard_parser_constructs (1);
247 /* Case of EOF seen by itself. Do ignoreeof or
249 global_command = (COMMAND *)NULL;
250 handle_eof_input_unit ();
256 { $$ = make_word_list ($1, (WORD_LIST *)NULL); }
258 { $$ = make_word_list ($2, $1); }
261 redirection: '>' WORD
264 $$ = make_redirection (1, r_output_direction, redir);
269 $$ = make_redirection (0, r_input_direction, redir);
274 $$ = make_redirection ($1, r_output_direction, redir);
279 $$ = make_redirection ($1, r_input_direction, redir);
281 | GREATER_GREATER WORD
284 $$ = make_redirection (1, r_appending_to, redir);
286 | NUMBER GREATER_GREATER WORD
289 $$ = make_redirection ($1, r_appending_to, redir);
294 $$ = make_redirection (0, r_reading_until, redir);
295 redir_stack[need_here_doc++] = $$;
297 | NUMBER LESS_LESS WORD
300 $$ = make_redirection ($1, r_reading_until, redir);
301 redir_stack[need_here_doc++] = $$;
306 $$ = make_redirection (0, r_duplicating_input, redir);
308 | NUMBER LESS_AND NUMBER
311 $$ = make_redirection ($1, r_duplicating_input, redir);
316 $$ = make_redirection (1, r_duplicating_output, redir);
318 | NUMBER GREATER_AND NUMBER
321 $$ = make_redirection ($1, r_duplicating_output, redir);
326 $$ = make_redirection (0, r_duplicating_input_word, redir);
328 | NUMBER LESS_AND WORD
331 $$ = make_redirection ($1, r_duplicating_input_word, redir);
336 $$ = make_redirection (1, r_duplicating_output_word, redir);
338 | NUMBER GREATER_AND WORD
341 $$ = make_redirection ($1, r_duplicating_output_word, redir);
343 | LESS_LESS_MINUS WORD
346 $$ = make_redirection
347 (0, r_deblank_reading_until, redir);
348 redir_stack[need_here_doc++] = $$;
350 | NUMBER LESS_LESS_MINUS WORD
353 $$ = make_redirection
354 ($1, r_deblank_reading_until, redir);
355 redir_stack[need_here_doc++] = $$;
360 $$ = make_redirection (1, r_close_this, redir);
362 | NUMBER GREATER_AND '-'
365 $$ = make_redirection ($1, r_close_this, redir);
370 $$ = make_redirection (0, r_close_this, redir);
372 | NUMBER LESS_AND '-'
375 $$ = make_redirection ($1, r_close_this, redir);
380 $$ = make_redirection (1, r_err_and_out, redir);
382 | NUMBER LESS_GREATER WORD
385 $$ = make_redirection ($1, r_input_output, redir);
390 $$ = make_redirection (0, r_input_output, redir);
395 $$ = make_redirection (1, r_output_force, redir);
397 | NUMBER GREATER_BAR WORD
400 $$ = make_redirection ($1, r_output_force, redir);
404 simple_command_element: WORD
405 { $$.word = $1; $$.redirect = 0; }
407 { $$.word = $1; $$.redirect = 0; }
409 { $$.redirect = $1; $$.word = 0; }
412 redirection_list: redirection
416 | redirection_list redirection
418 register REDIRECT *t;
420 for (t = $1; t->next; t = t->next)
427 simple_command: simple_command_element
428 { $$ = make_simple_command ($1, (COMMAND *)NULL); }
429 | simple_command simple_command_element
430 { $$ = make_simple_command ($2, $1); }
433 command: simple_command
434 { $$ = clean_simple_command ($1); }
437 | shell_command redirection_list
442 /* According to Posix.2 3.9.5, redirections
443 specified after the body of a function should
444 be attached to the function and performed when
445 the function is executed, not as part of the
446 function definition command. */
447 if (tc->type == cm_function_def)
449 tc = tc->value.Function_def->command;
450 if (tc->type == cm_group)
451 tc = tc->value.Group->command;
455 register REDIRECT *t;
456 for (t = tc->redirects; t->next; t = t->next)
466 shell_command: for_command
470 | WHILE compound_list DO compound_list DONE
471 { $$ = make_while_command ($2, $4); }
472 | UNTIL compound_list DO compound_list DONE
473 { $$ = make_until_command ($2, $4); }
486 for_command: FOR WORD newline_list DO compound_list DONE
487 { $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $5); }
488 | FOR WORD newline_list '{' compound_list '}'
489 { $$ = make_for_command ($2, add_string_to_list ("$@", (WORD_LIST *)NULL), $5); }
490 | FOR WORD ';' newline_list DO compound_list DONE
491 { $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6); }
492 | FOR WORD ';' newline_list '{' compound_list '}'
493 { $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6); }
494 | FOR WORD newline_list IN word_list list_terminator newline_list DO compound_list DONE
495 { $$ = make_for_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9); }
496 | FOR WORD newline_list IN word_list list_terminator newline_list '{' compound_list '}'
497 { $$ = make_for_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9); }
500 select_command: SELECT WORD newline_list DO list DONE
502 $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $5);
504 | SELECT WORD newline_list '{' list '}'
506 $$ = make_select_command ($2, add_string_to_list ("$@", (WORD_LIST *)NULL), $5);
508 | SELECT WORD ';' newline_list DO list DONE
510 $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6);
512 | SELECT WORD ';' newline_list '{' list '}'
514 $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6);
516 | SELECT WORD newline_list IN word_list list_terminator newline_list DO list DONE
518 $$ = make_select_command ($2, (WORD_LIST *)reverse_list ($5), $9);
520 | SELECT WORD newline_list IN word_list list_terminator newline_list '{' list '}'
522 $$ = make_select_command ($2, (WORD_LIST *)reverse_list ($5), $9);
526 case_command: CASE WORD newline_list IN newline_list ESAC
527 { $$ = make_case_command ($2, (PATTERN_LIST *)NULL); }
528 | CASE WORD newline_list IN case_clause_sequence newline_list ESAC
529 { $$ = make_case_command ($2, $5); }
530 | CASE WORD newline_list IN case_clause ESAC
531 { $$ = make_case_command ($2, $5); }
534 function_def: WORD '(' ')' newline_list group_command
535 { $$ = make_function_def ($1, $5, function_dstart, function_bstart); }
538 | FUNCTION WORD '(' ')' newline_list group_command
539 { $$ = make_function_def ($2, $6, function_dstart, function_bstart); }
541 | FUNCTION WORD newline_list group_command
542 { $$ = make_function_def ($2, $4, function_dstart, function_bstart); }
545 subshell: '(' compound_list ')'
546 { $2->flags |= CMD_WANT_SUBSHELL; $$ = $2; }
549 if_command: IF compound_list THEN compound_list FI
550 { $$ = make_if_command ($2, $4, (COMMAND *)NULL); }
551 | IF compound_list THEN compound_list ELSE compound_list FI
552 { $$ = make_if_command ($2, $4, $6); }
553 | IF compound_list THEN compound_list elif_clause FI
554 { $$ = make_if_command ($2, $4, $5); }
558 group_command: '{' list '}'
559 { $$ = make_group_command ($2); }
562 elif_clause: ELIF compound_list THEN compound_list
563 { $$ = make_if_command ($2, $4, (COMMAND *)NULL); }
564 | ELIF compound_list THEN compound_list ELSE compound_list
565 { $$ = make_if_command ($2, $4, $6); }
566 | ELIF compound_list THEN compound_list elif_clause
567 { $$ = make_if_command ($2, $4, $5); }
570 case_clause: pattern_list
571 | case_clause_sequence pattern_list
572 { $2->next = $1; $$ = $2; }
575 pattern_list: newline_list pattern ')' compound_list
576 { $$ = make_pattern_list ($2, $4); }
577 | newline_list pattern ')' newline_list
578 { $$ = make_pattern_list ($2, (COMMAND *)NULL); }
579 | newline_list '(' pattern ')' compound_list
580 { $$ = make_pattern_list ($3, $5); }
581 | newline_list '(' pattern ')' newline_list
582 { $$ = make_pattern_list ($3, (COMMAND *)NULL); }
585 case_clause_sequence: pattern_list SEMI_SEMI
586 | case_clause_sequence pattern_list SEMI_SEMI
587 { $2->next = $1; $$ = $2; }
591 { $$ = make_word_list ($1, (WORD_LIST *)NULL); }
593 { $$ = make_word_list ($3, $1); }
596 /* A list allows leading or trailing newlines and
597 newlines as operators (equivalent to semicolons).
598 It must end with a newline or semicolon.
599 Lists are used within commands such as if, for, while. */
601 list: newline_list list0
605 gather_here_documents ();
616 list0: list1 '\n' newline_list
617 | list1 '&' newline_list
619 if ($1->type == cm_connection)
620 $$ = connect_async_list ($1, (COMMAND *)NULL, '&');
622 $$ = command_connect ($1, (COMMAND *)NULL, '&');
624 | list1 ';' newline_list
628 list1: list1 AND_AND newline_list list1
629 { $$ = command_connect ($1, $4, AND_AND); }
630 | list1 OR_OR newline_list list1
631 { $$ = command_connect ($1, $4, OR_OR); }
632 | list1 '&' newline_list list1
634 if ($1->type == cm_connection)
635 $$ = connect_async_list ($1, $4, '&');
637 $$ = command_connect ($1, $4, '&');
639 | list1 ';' newline_list list1
640 { $$ = command_connect ($1, $4, ';'); }
641 | list1 '\n' newline_list list1
642 { $$ = command_connect ($1, $4, ';'); }
656 /* A simple_list is a list that contains no significant newlines
657 and no leading or trailing newlines. Newlines are allowed
658 only following operators, where they are not significant.
660 This is what an inputunit consists of. */
662 simple_list: simple_list1
666 gather_here_documents ();
670 if ($1->type == cm_connection)
671 $$ = connect_async_list ($1, (COMMAND *)NULL, '&');
673 $$ = command_connect ($1, (COMMAND *)NULL, '&');
675 gather_here_documents ();
681 gather_here_documents ();
685 simple_list1: simple_list1 AND_AND newline_list simple_list1
686 { $$ = command_connect ($1, $4, AND_AND); }
687 | simple_list1 OR_OR newline_list simple_list1
688 { $$ = command_connect ($1, $4, OR_OR); }
689 | simple_list1 '&' simple_list1
691 if ($1->type == cm_connection)
692 $$ = connect_async_list ($1, $3, '&');
694 $$ = command_connect ($1, $3, '&');
696 | simple_list1 ';' simple_list1
697 { $$ = command_connect ($1, $3, ';'); }
703 pipeline_command: pipeline
707 $2->flags |= CMD_INVERT_RETURN;
715 | timespec BANG pipeline
720 | BANG timespec pipeline
722 $3->flags |= $2|CMD_INVERT_RETURN;
728 pipeline '|' newline_list pipeline
729 { $$ = command_connect ($1, $4, '|'); }
735 { $$ = CMD_TIME_PIPELINE; }
737 { $$ = CMD_TIME_PIPELINE|CMD_TIME_POSIX; }
741 /* Possible states for the parser that require it to do special things. */
742 #define PST_CASEPAT 0x001 /* in a case pattern list */
743 #define PST_ALEXPNEXT 0x002 /* expand next word for aliases */
744 #define PST_ALLOWOPNBRC 0x004 /* allow open brace for function def */
745 #define PST_NEEDCLOSBRC 0x008 /* need close brace */
746 #define PST_DBLPAREN 0x010 /* double-paren parsing */
747 #define PST_SUBSHELL 0x020 /* ( ... ) subshell */
748 #define PST_CMDSUBST 0x040 /* $( ... ) command substitution */
749 #define PST_CASESTMT 0x080 /* parsing a case statement */
751 /* Initial size to allocate for tokens, and the
752 amount to grow them by. */
753 #define TOKEN_DEFAULT_INITIAL_SIZE 496
754 #define TOKEN_DEFAULT_GROW_SIZE 512
756 /* Shell meta-characters that, when unquoted, separate words. */
757 #define shellmeta(c) (strchr ("()<>;&|", (c)) != 0)
758 #define shellbreak(c) (strchr ("()<>;&| \t\n", (c)) != 0)
759 #define shellquote(c) ((c) == '"' || (c) == '`' || (c) == '\'')
760 #define shellexp(c) ((c) == '$' || (c) == '<' || (c) == '>')
762 /* The token currently being read. */
763 static int current_token;
765 /* The last read token, or NULL. read_token () uses this for context
767 static int last_read_token;
769 /* The token read prior to last_read_token. */
770 static int token_before_that;
772 /* The token read prior to token_before_that. */
773 static int two_tokens_ago;
775 /* If non-zero, it is the token that we want read_token to return
776 regardless of what text is (or isn't) present to be read. This
777 is reset by read_token. If token_to_read == WORD or
778 ASSIGNMENT_WORD, yylval.word should be set to word_desc_to_read. */
779 static int token_to_read;
780 static WORD_DESC *word_desc_to_read;
782 /* The current parser state. */
783 static int parser_state;
785 /* Global var is non-zero when end of file has been reached. */
797 /* yy_getc () returns the next available character from input or EOF.
798 yy_ungetc (c) makes `c' the next character to read.
799 init_yy_io (get, unget, type, location) makes the function GET the
800 installed function for getting the next character, makes UNGET the
801 installed function for un-getting a character, sets the type of stream
802 (either string or file) from TYPE, and makes LOCATION point to where
803 the input is coming from. */
805 /* Unconditionally returns end-of-file. */
812 /* Variable containing the current get and unget functions.
813 See ./input.h for a clearer description. */
814 BASH_INPUT bash_input;
816 /* Set all of the fields in BASH_INPUT to NULL. Free bash_input.name if it
817 is non-null, avoiding a memory leak. */
819 initialize_bash_input ()
821 bash_input.type = st_none;
822 FREE (bash_input.name);
823 bash_input.name = (char *)NULL;
824 bash_input.location.file = (FILE *)NULL;
825 bash_input.location.string = (char *)NULL;
826 bash_input.getter = (Function *)NULL;
827 bash_input.ungetter = (Function *)NULL;
830 /* Set the contents of the current bash input stream from
831 GET, UNGET, TYPE, NAME, and LOCATION. */
833 init_yy_io (get, unget, type, name, location)
834 Function *get, *unget;
835 enum stream_type type;
837 INPUT_STREAM location;
839 bash_input.type = type;
840 FREE (bash_input.name);
841 bash_input.name = name ? savestring (name) : (char *)NULL;
845 memcpy((char *)&bash_input.location.string, (char *)&location.string, sizeof(location));
847 bash_input.location = location;
849 bash_input.getter = get;
850 bash_input.ungetter = unget;
853 /* Call this to get the next character of input. */
857 return (*(bash_input.getter)) ();
860 /* Call this to unget C. That is, to make C the next character
866 return (*(bash_input.ungetter)) (c);
869 #if defined (BUFFERED_INPUT)
871 input_file_descriptor ()
873 switch (bash_input.type)
876 return (fileno (bash_input.location.file));
878 return (bash_input.location.buffered_fd);
881 return (fileno (stdin));
884 #endif /* BUFFERED_INPUT */
886 /* **************************************************************** */
888 /* Let input be read from readline (). */
890 /* **************************************************************** */
892 #if defined (READLINE)
893 char *current_readline_prompt = (char *)NULL;
894 char *current_readline_line = (char *)NULL;
895 int current_readline_line_index = 0;
900 SigHandler *old_sigint;
903 if (!current_readline_line)
905 if (!bash_readline_initialized)
906 initialize_readline ();
908 #if defined (JOB_CONTROL)
910 give_terminal_to (shell_pgrp);
911 #endif /* JOB_CONTROL */
913 if (signal_is_ignored (SIGINT) == 0)
915 old_sigint = (SigHandler *)set_signal_handler (SIGINT, sigint_sighandler);
916 interrupt_immediately++;
919 current_readline_line = readline (current_readline_prompt ?
920 current_readline_prompt : "");
922 if (signal_is_ignored (SIGINT) == 0)
924 interrupt_immediately--;
925 set_signal_handler (SIGINT, old_sigint);
929 /* Reset the prompt to the decoded value of prompt_string_pointer. */
930 reset_readline_prompt ();
933 if (current_readline_line == 0)
936 current_readline_line_index = 0;
937 line_len = strlen (current_readline_line);
939 current_readline_line = xrealloc (current_readline_line, 2 + line_len);
940 current_readline_line[line_len++] = '\n';
941 current_readline_line[line_len] = '\0';
944 if (current_readline_line[current_readline_line_index] == 0)
946 free (current_readline_line);
947 current_readline_line = (char *)NULL;
948 return (yy_readline_get ());
952 c = (unsigned char)current_readline_line[current_readline_line_index++];
958 yy_readline_unget (c)
961 if (current_readline_line_index && current_readline_line)
962 current_readline_line[--current_readline_line_index] = c;
967 with_input_from_stdin ()
969 INPUT_STREAM location;
971 if (bash_input.type != st_stdin && stream_on_stack (st_stdin) == 0)
973 location.string = current_readline_line;
974 init_yy_io (yy_readline_get, yy_readline_unget,
975 st_stdin, "readline stdin", location);
979 #else /* !READLINE */
982 with_input_from_stdin ()
984 with_input_from_stream (stdin, "stdin");
986 #endif /* !READLINE */
988 /* **************************************************************** */
990 /* Let input come from STRING. STRING is zero terminated. */
992 /* **************************************************************** */
997 register char *string;
1000 string = bash_input.location.string;
1003 /* If the string doesn't exist, or is empty, EOF found. */
1004 if (string && *string)
1006 c = *(unsigned char *)string++;
1007 bash_input.location.string = string;
1016 *(--bash_input.location.string) = c;
1021 with_input_from_string (string, name)
1022 char *string, *name;
1024 INPUT_STREAM location;
1026 location.string = string;
1027 init_yy_io (yy_string_get, yy_string_unget, st_string, name, location);
1030 /* **************************************************************** */
1032 /* Let input come from STREAM. */
1034 /* **************************************************************** */
1041 if (bash_input.location.file)
1043 #if !defined (HAVE_RESTARTABLE_SYSCALLS)
1044 result = getc_with_restart (bash_input.location.file);
1045 #else /* HAVE_RESTARTABLE_SYSCALLS */
1046 result = getc (bash_input.location.file);
1047 result = (feof (bash_input.location.file)) ? EOF : (unsigned char)result;
1048 #endif /* HAVE_RESTARTABLE_SYSCALLS */
1057 #if !defined (HAVE_RESTARTABLE_SYSCALLS)
1058 return (ungetc_with_restart (c, bash_input.location.file));
1059 #else /* HAVE_RESTARTABLE_SYSCALLS */
1060 return (ungetc (c, bash_input.location.file));
1061 #endif /* HAVE_RESTARTABLE_SYSCALLS */
1065 with_input_from_stream (stream, name)
1069 INPUT_STREAM location;
1071 location.file = stream;
1072 init_yy_io (yy_stream_get, yy_stream_unget, st_stream, name, location);
1075 typedef struct stream_saver {
1076 struct stream_saver *next;
1077 BASH_INPUT bash_input;
1079 #if defined (BUFFERED_INPUT)
1080 BUFFERED_STREAM *bstream;
1081 #endif /* BUFFERED_INPUT */
1084 /* The globally known line number. */
1085 int line_number = 0;
1087 STREAM_SAVER *stream_list = (STREAM_SAVER *)NULL;
1090 push_stream (reset_lineno)
1093 STREAM_SAVER *saver = (STREAM_SAVER *)xmalloc (sizeof (STREAM_SAVER));
1095 xbcopy ((char *)&bash_input, (char *)&(saver->bash_input), sizeof (BASH_INPUT));
1097 #if defined (BUFFERED_INPUT)
1098 saver->bstream = (BUFFERED_STREAM *)NULL;
1099 /* If we have a buffered stream, clear out buffers[fd]. */
1100 if (bash_input.type == st_bstream && bash_input.location.buffered_fd >= 0)
1102 saver->bstream = buffers[bash_input.location.buffered_fd];
1103 buffers[bash_input.location.buffered_fd] = (BUFFERED_STREAM *)NULL;
1105 #endif /* BUFFERED_INPUT */
1107 saver->line = line_number;
1108 bash_input.name = (char *)NULL;
1109 saver->next = stream_list;
1110 stream_list = saver;
1123 STREAM_SAVER *saver = stream_list;
1126 stream_list = stream_list->next;
1128 init_yy_io (saver->bash_input.getter,
1129 saver->bash_input.ungetter,
1130 saver->bash_input.type,
1131 saver->bash_input.name,
1132 saver->bash_input.location);
1134 #if defined (BUFFERED_INPUT)
1135 /* If we have a buffered stream, restore buffers[fd]. */
1136 /* If the input file descriptor was changed while this was on the
1137 save stack, update the buffered fd to the new file descriptor and
1138 re-establish the buffer <-> bash_input fd correspondence. */
1139 if (bash_input.type == st_bstream && bash_input.location.buffered_fd >= 0)
1141 if (bash_input_fd_changed)
1143 bash_input_fd_changed = 0;
1144 if (default_buffered_input >= 0)
1146 bash_input.location.buffered_fd = default_buffered_input;
1147 saver->bstream->b_fd = default_buffered_input;
1150 buffers[bash_input.location.buffered_fd] = saver->bstream;
1152 #endif /* BUFFERED_INPUT */
1154 line_number = saver->line;
1156 FREE (saver->bash_input.name);
1161 /* Return 1 if a stream of type TYPE is saved on the stack. */
1163 stream_on_stack (type)
1164 enum stream_type type;
1166 register STREAM_SAVER *s;
1168 for (s = stream_list; s; s = s->next)
1169 if (s->bash_input.type == type)
1175 * This is used to inhibit alias expansion and reserved word recognition
1176 * inside case statement pattern lists. A `case statement pattern list' is:
1178 * everything between the `in' in a `case word in' and the next ')'
1180 * everything between a `;;' and the next `)' or `esac'
1185 #define END_OF_ALIAS 0
1188 * Pseudo-global variables used in implementing token-wise alias expansion.
1192 * Pushing and popping strings. This works together with shell_getc to
1193 * implement alias expansion on a per-token basis.
1196 typedef struct string_saver {
1197 struct string_saver *next;
1198 int expand_alias; /* Value to set expand_alias to when string is popped. */
1200 alias_t *expander; /* alias that caused this line to be pushed. */
1201 int saved_line_size, saved_line_index, saved_line_terminator;
1204 STRING_SAVER *pushed_string_list = (STRING_SAVER *)NULL;
1207 * Push the current shell_input_line onto a stack of such lines and make S
1208 * the current input. Used when expanding aliases. EXPAND is used to set
1209 * the value of expand_next_token when the string is popped, so that the
1210 * word after the alias in the original line is handled correctly when the
1211 * alias expands to multiple words. TOKEN is the token that was expanded
1212 * into S; it is saved and used to prevent infinite recursive expansion.
1215 push_string (s, expand, ap)
1220 STRING_SAVER *temp = (STRING_SAVER *) xmalloc (sizeof (STRING_SAVER));
1222 temp->expand_alias = expand;
1223 temp->saved_line = shell_input_line;
1224 temp->saved_line_size = shell_input_line_size;
1225 temp->saved_line_index = shell_input_line_index;
1226 temp->saved_line_terminator = shell_input_line_terminator;
1227 temp->expander = ap;
1228 temp->next = pushed_string_list;
1229 pushed_string_list = temp;
1232 ap->flags |= AL_BEINGEXPANDED;
1234 shell_input_line = s;
1235 shell_input_line_size = strlen (s);
1236 shell_input_line_index = 0;
1237 shell_input_line_terminator = '\0';
1238 parser_state &= ~PST_ALEXPNEXT;
1242 * Make the top of the pushed_string stack be the current shell input.
1243 * Only called when there is something on the stack. Called from shell_getc
1244 * when it thinks it has consumed the string generated by an alias expansion
1245 * and needs to return to the original input line.
1252 FREE (shell_input_line);
1253 shell_input_line = pushed_string_list->saved_line;
1254 shell_input_line_index = pushed_string_list->saved_line_index;
1255 shell_input_line_size = pushed_string_list->saved_line_size;
1256 shell_input_line_terminator = pushed_string_list->saved_line_terminator;
1258 if (pushed_string_list->expand_alias)
1259 parser_state |= PST_ALEXPNEXT;
1261 parser_state &= ~PST_ALEXPNEXT;
1263 t = pushed_string_list;
1264 pushed_string_list = pushed_string_list->next;
1267 t->expander->flags &= ~AL_BEINGEXPANDED;
1275 register STRING_SAVER *t, *t1;
1277 for (t = pushed_string_list; t; )
1280 FREE (t->saved_line);
1281 t->expander->flags &= ~AL_BEINGEXPANDED;
1285 pushed_string_list = (STRING_SAVER *)NULL;
1290 /* Return a line of text, taken from wherever yylex () reads input.
1291 If there is no more input, then we return NULL. If REMOVE_QUOTED_NEWLINE
1292 is non-zero, we remove unquoted \<newline> pairs. This is used by
1293 read_secondary_line to read here documents. */
1295 read_a_line (remove_quoted_newline)
1296 int remove_quoted_newline;
1298 static char *line_buffer = (char *)NULL;
1299 static int buffer_size = 0;
1300 int indx = 0, c, peekc, pass_next;
1302 #if defined (READLINE)
1303 if (interactive && bash_input.type != st_string && no_line_editing)
1305 if (interactive && bash_input.type != st_string)
1314 /* Allow immediate exit if interrupted during input. */
1320 /* If there is no more input, then we return NULL. */
1323 if (interactive && bash_input.type == st_stream)
1326 return ((char *)NULL);
1330 /* `+2' in case the final character in the buffer is a newline. */
1331 RESIZE_MALLOCED_BUFFER (line_buffer, indx, 2, buffer_size, 128);
1333 /* IF REMOVE_QUOTED_NEWLINES is non-zero, we are reading a
1334 here document with an unquoted delimiter. In this case,
1335 the line will be expanded as if it were in double quotes.
1336 We allow a backslash to escape the next character, but we
1337 need to treat the backslash specially only if a backslash
1338 quoting a backslash-newline pair appears in the line. */
1341 line_buffer[indx++] = c;
1344 else if (c == '\\' && remove_quoted_newline)
1348 continue; /* Make the unquoted \<newline> pair disappear. */
1353 line_buffer[indx++] = c; /* Preserve the backslash. */
1357 line_buffer[indx++] = c;
1361 line_buffer[indx] = '\0';
1362 return (line_buffer);
1367 /* Return a line as in read_a_line (), but insure that the prompt is
1368 the secondary prompt. This is used to read the lines of a here
1369 document. REMOVE_QUOTED_NEWLINE is non-zero if we should remove
1370 newlines quoted with backslashes while reading the line. It is
1371 non-zero unless the delimiter of the here document was quoted. */
1373 read_secondary_line (remove_quoted_newline)
1374 int remove_quoted_newline;
1376 prompt_string_pointer = &ps2_prompt;
1378 return (read_a_line (remove_quoted_newline));
1381 /* **************************************************************** */
1385 /* **************************************************************** */
1387 /* Reserved words. These are only recognized as the first word of a
1389 STRING_INT_ALIST word_token_alist[] = {
1398 #if defined (SELECT_COMMAND)
1399 { "select", SELECT },
1406 { "function", FUNCTION },
1407 #if defined (COMMAND_TIMING)
1416 /* These are used by read_token_word, but appear up here so that shell_getc
1417 can use them to decide when to add otherwise blank lines to the history. */
1419 /* The primary delimiter stack. */
1420 struct dstack dstack = { (char *)NULL, 0, 0 };
1422 /* A temporary delimiter stack to be used when decoding prompt strings.
1423 This is needed because command substitutions in prompt strings (e.g., PS2)
1424 can screw up the parser's quoting state. */
1425 static struct dstack temp_dstack = { (char *)NULL, 0, 0 };
1427 /* Macro for accessing the top delimiter on the stack. Returns the
1428 delimiter or zero if none. */
1429 #define current_delimiter(ds) \
1430 (ds.delimiter_depth ? ds.delimiters[ds.delimiter_depth - 1] : 0)
1432 #define push_delimiter(ds, character) \
1435 if (ds.delimiter_depth + 2 > ds.delimiter_space) \
1436 ds.delimiters = xrealloc \
1437 (ds.delimiters, (ds.delimiter_space += 10) * sizeof (char)); \
1438 ds.delimiters[ds.delimiter_depth] = character; \
1439 ds.delimiter_depth++; \
1443 #define pop_delimiter(ds) ds.delimiter_depth--
1445 /* Return the next shell input character. This always reads characters
1446 from shell_input_line; when that line is exhausted, it is time to
1447 read the next line. This is called by read_token when the shell is
1448 processing normal command input. */
1451 shell_getc (remove_quoted_newline)
1452 int remove_quoted_newline;
1456 static int mustpop = 0;
1461 /* If shell_input_line[shell_input_line_index] == 0, but there is
1462 something on the pushed list of strings, then we don't want to go
1463 off and get another line. We let the code down below handle it. */
1465 if (!shell_input_line || ((!shell_input_line[shell_input_line_index]) &&
1466 (pushed_string_list == (STRING_SAVER *)NULL)))
1468 if (!shell_input_line || !shell_input_line[shell_input_line_index])
1475 /* Allow immediate exit if interrupted during input. */
1479 shell_input_line_terminator = 0;
1481 #if defined (JOB_CONTROL)
1482 /* This can cause a problem when reading a command as the result
1483 of a trap, when the trap is called from flush_child. This call
1484 had better not cause jobs to disappear from the job table in
1485 that case, or we will have big trouble. */
1486 notify_and_cleanup ();
1487 #else /* !JOB_CONTROL */
1488 cleanup_dead_jobs ();
1489 #endif /* !JOB_CONTROL */
1491 #if defined (READLINE)
1492 if (interactive && bash_input.type != st_string && no_line_editing)
1494 if (interactive && bash_input.type != st_string)
1498 if (bash_input.type == st_stream)
1501 while (c = yy_getc ())
1503 /* Allow immediate exit if interrupted during input. */
1506 RESIZE_MALLOCED_BUFFER (shell_input_line, i, 2, shell_input_line_size, 256);
1510 if (bash_input.type == st_stream)
1514 shell_input_line_terminator = EOF;
1516 shell_input_line[i] = '\0';
1520 shell_input_line[i++] = c;
1524 shell_input_line[--i] = '\0';
1525 current_command_line_count++;
1529 shell_input_line_index = 0;
1530 shell_input_line_len = i; /* == strlen (shell_input_line) */
1532 #if defined (HISTORY)
1533 if (remember_on_history && shell_input_line && shell_input_line[0])
1536 # if defined (BANG_HISTORY)
1539 /* If the current delimiter is a single quote, we should not be
1540 performing history expansion, even if we're on a different
1541 line from the original single quote. */
1542 old_hist = history_expansion_inhibited;
1543 if (current_delimiter (dstack) == '\'')
1544 history_expansion_inhibited = 1;
1546 expansions = pre_process_line (shell_input_line, 1, 1);
1547 # if defined (BANG_HISTORY)
1548 history_expansion_inhibited = old_hist;
1550 if (expansions != shell_input_line)
1552 free (shell_input_line);
1553 shell_input_line = expansions;
1554 shell_input_line_len = shell_input_line ?
1555 strlen (shell_input_line) : 0;
1556 if (!shell_input_line_len)
1557 current_command_line_count--;
1559 /* We have to force the xrealloc below because we don't know
1560 the true allocated size of shell_input_line anymore. */
1561 shell_input_line_size = shell_input_line_len;
1564 /* XXX - this is grotesque */
1565 else if (remember_on_history && shell_input_line &&
1566 shell_input_line[0] == '\0' &&
1567 current_command_line_count > 1 && current_delimiter (dstack))
1569 /* We know shell_input_line[0] == 0 and we're reading some sort of
1570 quoted string. This means we've got a line consisting of only
1571 a newline in a quoted string. We want to make sure this line
1572 gets added to the history. */
1573 maybe_add_history (shell_input_line);
1576 #endif /* HISTORY */
1578 if (shell_input_line)
1580 /* Lines that signify the end of the shell's input should not be
1582 if (echo_input_at_read && (shell_input_line[0] ||
1583 shell_input_line_terminator != EOF))
1584 fprintf (stderr, "%s\n", shell_input_line);
1588 shell_input_line_size = 0;
1589 prompt_string_pointer = ¤t_prompt_string;
1594 /* Add the newline to the end of this string, iff the string does
1595 not already end in an EOF character. */
1596 if (shell_input_line_terminator != EOF)
1598 if (shell_input_line_len + 3 > shell_input_line_size)
1599 shell_input_line = xrealloc (shell_input_line,
1600 1 + (shell_input_line_size += 2));
1602 shell_input_line[shell_input_line_len] = '\n';
1603 shell_input_line[shell_input_line_len + 1] = '\0';
1607 c = shell_input_line[shell_input_line_index];
1610 shell_input_line_index++;
1612 if (c == '\\' && remove_quoted_newline &&
1613 shell_input_line[shell_input_line_index] == '\n')
1621 /* If C is NULL, we have reached the end of the current input string. If
1622 pushed_string_list is non-empty, it's time to pop to the previous string
1623 because we have fully consumed the result of the last alias expansion.
1624 Do it transparently; just return the next character of the string popped
1626 if (!c && (pushed_string_list != (STRING_SAVER *)NULL))
1631 c = shell_input_line[shell_input_line_index];
1633 shell_input_line_index++;
1644 if (!c && shell_input_line_terminator == EOF)
1645 return ((shell_input_line_index != 0) ? '\n' : EOF);
1647 return ((unsigned char)c);
1650 /* Put C back into the input for the shell. */
1655 if (shell_input_line && shell_input_line_index)
1656 shell_input_line[--shell_input_line_index] = c;
1662 if (shell_input_line && shell_input_line_index)
1663 shell_input_line_index--;
1666 /* Discard input until CHARACTER is seen, then push that character back
1667 onto the input stream. */
1669 discard_until (character)
1674 while ((c = shell_getc (0)) != EOF && c != character)
1682 execute_prompt_command (command)
1685 Function *temp_last, *temp_this;
1687 int temp_exit_value, temp_eof_encountered;
1689 temp_last = last_shell_builtin;
1690 temp_this = this_shell_builtin;
1691 temp_exit_value = last_command_exit_value;
1692 temp_eof_encountered = eof_encountered;
1693 last_lastarg = get_string_value ("_");
1695 last_lastarg = savestring (last_lastarg);
1697 parse_and_execute (savestring (command), "PROMPT_COMMAND", SEVAL_NONINT|SEVAL_NOHIST);
1699 last_shell_builtin = temp_last;
1700 this_shell_builtin = temp_this;
1701 last_command_exit_value = temp_exit_value;
1702 eof_encountered = temp_eof_encountered;
1704 bind_variable ("_", last_lastarg);
1705 FREE (last_lastarg);
1707 if (token_to_read == '\n') /* reset_parser was called */
1711 /* Place to remember the token. We try to keep the buffer
1712 at a reasonable size, but it can grow. */
1713 static char *token = (char *)NULL;
1715 /* Current size of the token buffer. */
1716 static int token_buffer_size;
1718 /* Command to read_token () explaining what we want it to do. */
1721 #define prompt_is_ps1 \
1722 (!prompt_string_pointer || prompt_string_pointer == &ps1_prompt)
1724 /* Function for yyparse to call. yylex keeps track of
1725 the last two tokens read, and calls read_token. */
1729 if (interactive && (current_token == 0 || current_token == '\n'))
1731 /* Before we print a prompt, we might have to check mailboxes.
1732 We do this only if it is time to do so. Notice that only here
1733 is the mail alarm reset; nothing takes place in check_mail ()
1734 except the checking of mail. Please don't change this. */
1735 if (prompt_is_ps1 && time_to_check_mail ())
1738 reset_mail_timer ();
1741 /* Avoid printing a prompt if we're not going to read anything, e.g.
1742 after resetting the parser with read_token (RESET). */
1743 if (token_to_read == 0 && interactive)
1747 two_tokens_ago = token_before_that;
1748 token_before_that = last_read_token;
1749 last_read_token = current_token;
1750 current_token = read_token (READ);
1751 return (current_token);
1754 /* When non-zero, we have read the required tokens
1755 which allow ESAC to be the next one read. */
1756 static int esacs_needed_count;
1759 gather_here_documents ()
1762 while (need_here_doc)
1764 make_here_document (redir_stack[r++]);
1769 /* When non-zero, an open-brace used to create a group is awaiting a close
1771 static int open_brace_count;
1773 #define command_token_position(token) \
1774 (((token) == ASSIGNMENT_WORD) || \
1775 ((token) != SEMI_SEMI && reserved_word_acceptable(token)))
1777 #define assignment_acceptable(token) command_token_position(token) && \
1778 ((parser_state & PST_CASEPAT) == 0)
1780 /* Check to see if TOKEN is a reserved word and return the token
1782 #define CHECK_FOR_RESERVED_WORD(tok) \
1784 if (!dollar_present && !quoted && \
1785 reserved_word_acceptable (last_read_token)) \
1788 for (i = 0; word_token_alist[i].word != (char *)NULL; i++) \
1789 if (STREQ (tok, word_token_alist[i].word)) \
1791 if ((parser_state & PST_CASEPAT) && (word_token_alist[i].token != ESAC)) \
1793 if (word_token_alist[i].token == ESAC) \
1794 parser_state &= ~(PST_CASEPAT|PST_CASESTMT); \
1795 else if (word_token_alist[i].token == CASE) \
1796 parser_state |= PST_CASESTMT; \
1797 else if (word_token_alist[i].token == '{') \
1798 open_brace_count++; \
1799 else if (word_token_alist[i].token == '}' && open_brace_count) \
1800 open_brace_count--; \
1801 return (word_token_alist[i].token); \
1808 /* OK, we have a token. Let's try to alias expand it, if (and only if)
1811 It is eligible for expansion if the shell is in interactive mode, and
1812 the token is unquoted and the last token read was a command
1813 separator (or expand_next_token is set), and we are currently
1814 processing an alias (pushed_string_list is non-empty) and this
1815 token is not the same as the current or any previously
1818 Special cases that disqualify:
1819 In a pattern list in a case statement (parser_state & PST_CASEPAT). */
1821 alias_expand_token (token)
1827 if (((parser_state & PST_ALEXPNEXT) || command_token_position (last_read_token)) &&
1828 (parser_state & PST_CASEPAT) == 0)
1830 ap = find_alias (token);
1832 /* Currently expanding this token. */
1833 if (ap && (ap->flags & AL_BEINGEXPANDED))
1834 return (NO_EXPANSION);
1836 expanded = ap ? savestring (ap->value) : (char *)NULL;
1839 push_string (expanded, ap->flags & AL_EXPANDNEXT, ap);
1840 return (RE_READ_TOKEN);
1843 /* This is an eligible token that does not have an expansion. */
1844 return (NO_EXPANSION);
1846 return (NO_EXPANSION);
1850 /* Handle special cases of token recognition:
1851 IN is recognized if the last token was WORD and the token
1852 before that was FOR or CASE or SELECT.
1854 DO is recognized if the last token was WORD and the token
1855 before that was FOR or SELECT.
1857 ESAC is recognized if the last token caused `esacs_needed_count'
1860 `{' is recognized if the last token as WORD and the token
1861 before that was FUNCTION.
1863 `}' is recognized if there is an unclosed `{' prsent.
1867 special_case_tokens (token)
1870 if ((last_read_token == WORD) &&
1871 #if defined (SELECT_COMMAND)
1872 ((token_before_that == FOR) || (token_before_that == CASE) || (token_before_that == SELECT)) &&
1874 ((token_before_that == FOR) || (token_before_that == CASE)) &&
1876 (token[0] == 'i' && token[1] == 'n' && token[2] == 0))
1878 if (token_before_that == CASE)
1880 parser_state |= PST_CASEPAT;
1881 esacs_needed_count++;
1886 if (last_read_token == WORD &&
1887 #if defined (SELECT_COMMAND)
1888 (token_before_that == FOR || token_before_that == SELECT) &&
1890 (token_before_that == FOR) &&
1892 (token[0] == 'd' && token[1] == 'o' && token[2] == '\0'))
1895 /* Ditto for ESAC in the CASE case.
1896 Specifically, this handles "case word in esac", which is a legal
1897 construct, certainly because someone will pass an empty arg to the
1898 case construct, and we don't want it to barf. Of course, we should
1899 insist that the case construct has at least one pattern in it, but
1900 the designers disagree. */
1901 if (esacs_needed_count)
1903 esacs_needed_count--;
1904 if (STREQ (token, "esac"))
1906 parser_state &= ~PST_CASEPAT;
1911 /* The start of a shell function definition. */
1912 if (parser_state & PST_ALLOWOPNBRC)
1914 parser_state &= ~PST_ALLOWOPNBRC;
1915 if (token[0] == '{' && token[1] == '\0') /* } */
1918 function_bstart = line_number;
1919 return ('{'); /* } */
1923 if (open_brace_count && reserved_word_acceptable (last_read_token) && token[0] == '}' && !token[1])
1925 open_brace_count--; /* { */
1929 /* Handle -p after `time'. */
1930 if (last_read_token == TIME && token[0] == '-' && token[1] == 'p' && !token[2])
1936 /* Called from shell.c when Control-C is typed at top level. Or
1937 by the error rule at top level. */
1941 dstack.delimiter_depth = 0; /* No delimiters found so far. */
1942 open_brace_count = 0;
1947 if (pushed_string_list)
1949 free_string_list ();
1950 pushed_string_list = (STRING_SAVER *)NULL;
1954 if (shell_input_line)
1956 free (shell_input_line);
1957 shell_input_line = (char *)NULL;
1958 shell_input_line_size = shell_input_line_index = 0;
1961 FREE (word_desc_to_read);
1962 word_desc_to_read = (WORD_DESC *)NULL;
1964 last_read_token = '\n';
1965 token_to_read = '\n';
1968 /* Read the next token. Command can be READ (normal operation) or
1969 RESET (to normalize state). */
1971 read_token (command)
1974 int character; /* Current character. */
1975 int peek_char; /* Temporary look-ahead character. */
1976 int result; /* The thing to return. */
1978 if (command == RESET)
1986 result = token_to_read;
1987 if (token_to_read == WORD || token_to_read == ASSIGNMENT_WORD)
1989 yylval.word = word_desc_to_read;
1990 word_desc_to_read = (WORD_DESC *)NULL;
1997 /* This is a place to jump back to once we have successfully expanded a
1998 token with an alias and pushed the string with push_string () */
2002 /* Read a single word from input. Start by skipping blanks. */
2003 while ((character = shell_getc (1)) != EOF && whitespace (character))
2006 if (character == EOF)
2012 if (character == '#' && (!interactive || interactive_comments))
2014 /* A comment. Discard until EOL or EOF, and then return a newline. */
2015 discard_until ('\n');
2017 character = '\n'; /* this will take the next if statement and return. */
2020 if (character == '\n')
2022 /* If we're about to return an unquoted newline, we can go and collect
2023 the text of any pending here document. */
2025 gather_here_documents ();
2028 parser_state &= ~PST_ALEXPNEXT;
2034 /* Shell meta-characters. */
2035 if (shellmeta (character) && ((parser_state & PST_DBLPAREN) == 0))
2038 /* Turn off alias tokenization iff this character sequence would
2039 not leave us ready to read a command. */
2040 if (character == '<' || character == '>')
2041 parser_state &= ~PST_ALEXPNEXT;
2044 peek_char = shell_getc (1);
2045 if (character == peek_char)
2050 /* If '<' then we could be at "<<" or at "<<-". We have to
2051 look ahead one more character. */
2052 peek_char = shell_getc (1);
2053 if (peek_char == '-')
2054 return (LESS_LESS_MINUS);
2057 shell_ungetc (peek_char);
2062 return (GREATER_GREATER);
2065 parser_state |= PST_CASEPAT;
2067 parser_state &= ~PST_ALEXPNEXT;
2077 #if defined (DPAREN_ARITHMETIC)
2079 if (reserved_word_acceptable (last_read_token))
2084 sline = line_number;
2085 cmdtyp = parse_arith_cmd (&wval);
2086 if (cmdtyp == 1) /* arithmetic command */
2088 word_desc_to_read = make_word (wval);
2089 word_desc_to_read->flags = W_QUOTED;
2090 token_to_read = WORD;
2092 yylval.word = make_word ("let");
2095 else if (cmdtyp == 0) /* nested subshell */
2097 push_string (wval, 0, (alias_t *)NULL);
2098 if ((parser_state & PST_CASEPAT) == 0)
2099 parser_state |= PST_SUBSHELL;
2109 else if (character == '<' && peek_char == '&')
2111 else if (character == '>' && peek_char == '&')
2112 return (GREATER_AND);
2113 else if (character == '<' && peek_char == '>')
2114 return (LESS_GREATER);
2115 else if (character == '>' && peek_char == '|')
2116 return (GREATER_BAR);
2117 else if (peek_char == '>' && character == '&')
2118 return (AND_GREATER);
2120 shell_ungetc (peek_char);
2122 /* If we look like we are reading the start of a function
2123 definition, then let the reader know about it so that
2124 we will do the right thing with `{'. */
2125 if (character == ')' && last_read_token == '(' && token_before_that == WORD)
2127 parser_state |= PST_ALLOWOPNBRC;
2129 parser_state &= ~PST_ALEXPNEXT;
2131 function_dstart = line_number;
2134 /* case pattern lists may be preceded by an optional left paren. If
2135 we're not trying to parse a case pattern list, the left paren
2136 indicates a subshell. */
2137 if (character == '(' && (parser_state & PST_CASEPAT) == 0) /* ) */
2138 parser_state |= PST_SUBSHELL;
2140 else if ((parser_state & PST_CASEPAT) && character == ')')
2141 parser_state &= ~PST_CASEPAT;
2143 else if ((parser_state & PST_SUBSHELL) && character == ')')
2144 parser_state &= ~PST_SUBSHELL;
2146 #if defined (PROCESS_SUBSTITUTION)
2147 /* Check for the constructs which introduce process substitution.
2148 Shells running in `posix mode' don't do process substitution. */
2149 if (posixly_correct ||
2150 ((character != '>' && character != '<') || peek_char != '('))
2151 #endif /* PROCESS_SUBSTITUTION */
2155 /* Hack <&- (close stdin) case. */
2156 if (character == '-' && (last_read_token == LESS_AND || last_read_token == GREATER_AND))
2159 /* Okay, if we got this far, we have to read a word. Read one,
2160 and then check it against the known ones. */
2161 result = read_token_word (character);
2163 if (result == RE_READ_TOKEN)
2169 /* Match a $(...) or other grouping construct. This has to handle embedded
2170 quoted strings ('', ``, "") and nested constructs. It also must handle
2171 reprompting the user, if necessary, after reading a newline, and returning
2172 correct error values if it reads EOF. */
2173 static char matched_pair_error;
2175 parse_matched_pair (qc, open, close, lenp, flags)
2176 int qc; /* `"' if this construct is within double quotes */
2180 int count, ch, was_dollar;
2181 int pass_next_character, nestlen, start_lineno;
2182 char *ret, *nestret;
2183 int retind, retsize;
2186 pass_next_character = was_dollar = 0;
2188 ret = xmalloc (retsize = 64);
2191 start_lineno = line_number;
2194 ch = shell_getc (qc != '\'' && pass_next_character == 0);
2198 parser_error (start_lineno, "unexpected EOF while looking for matching `%c'", close);
2199 EOF_Reached = 1; /* XXX */
2200 return (&matched_pair_error);
2203 /* Possible reprompting. */
2204 if (ch == '\n' && interactive &&
2205 (bash_input.type == st_stdin || bash_input.type == st_stream))
2208 if (pass_next_character) /* last char was backslash */
2210 pass_next_character = 0;
2211 if (qc != '\'' && ch == '\n') /* double-quoted \<newline> disappears. */
2213 if (retind > 0) retind--; /* swallow previously-added backslash */
2217 RESIZE_MALLOCED_BUFFER (ret, retind, 2, retsize, 64);
2218 if (ch == CTLESC || ch == CTLNUL)
2219 ret[retind++] = CTLESC;
2223 else if (ch == CTLESC || ch == CTLNUL) /* special shell escapes */
2225 RESIZE_MALLOCED_BUFFER (ret, retind, 2, retsize, 64);
2226 ret[retind++] = CTLESC;
2230 else if (ch == close) /* ending delimiter */
2232 else if (ch == open) /* nested begin */
2235 /* Add this character. */
2236 RESIZE_MALLOCED_BUFFER (ret, retind, 1, retsize, 64);
2239 if (open == '\'') /* '' inside grouping construct */
2242 if (ch == '\\') /* backslashes */
2243 pass_next_character++;
2245 if (open != close) /* a grouping construct */
2247 if (shellquote (ch))
2249 /* '', ``, or "" inside $(...) or other grouping construct. */
2250 push_delimiter (dstack, ch);
2251 nestret = parse_matched_pair (ch, ch, ch, &nestlen, 0);
2252 pop_delimiter (dstack);
2253 if (nestret == &matched_pair_error)
2256 return &matched_pair_error;
2260 RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2261 strcpy (ret + retind, nestret);
2267 /* Parse an old-style command substitution within double quotes as a
2269 /* XXX - sh and ksh93 don't do this - XXX */
2270 else if (open == '"' && ch == '`')
2272 nestret = parse_matched_pair (0, '`', '`', &nestlen, 0);
2273 if (nestret == &matched_pair_error)
2276 return &matched_pair_error;
2280 RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2281 strcpy (ret + retind, nestret);
2286 else if (was_dollar && (ch == '(' || ch == '{' || ch == '[')) /* ) } ] */
2287 /* check for $(), $[], or ${} inside quoted string. */
2289 if (open == ch) /* undo previous increment */
2291 if (ch == '(') /* ) */
2292 nestret = parse_matched_pair (0, '(', ')', &nestlen, 0);
2293 else if (ch == '{') /* } */
2294 nestret = parse_matched_pair (0, '{', '}', &nestlen, 0);
2295 else if (ch == '[') /* ] */
2296 nestret = parse_matched_pair (0, '[', ']', &nestlen, 0);
2297 if (nestret == &matched_pair_error)
2300 return &matched_pair_error;
2304 RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2305 strcpy (ret + retind, nestret);
2310 was_dollar = (ch == '$');
2319 #if defined (DPAREN_ARITHMETIC)
2320 /* We've seen a `(('. Look for the matching `))'. If we get it, return 1.
2321 If not, assume it's a nested subshell for backwards compatibility and
2322 return 0. In any case, put the characters we've consumed into a locally-
2323 allocated buffer and make *ep point to that buffer. Return -1 on an
2324 error, for example EOF. */
2326 parse_arith_cmd (ep)
2329 int exp_lineno, rval, c;
2333 exp_lineno = line_number;
2334 ttok = parse_matched_pair (0, '(', ')', &ttoklen, 0);
2336 if (ttok == &matched_pair_error)
2338 /* Check that the next character is the closing right paren. If
2339 not, this is a syntax error. ( */
2340 if ((c = shell_getc (0)) != ')')
2343 token = xmalloc(ttoklen + 4);
2345 /* (( ... )) -> "..." */
2346 token[0] = (rval == 1) ? '"' : '(';
2347 strncpy (token + 1, ttok, ttoklen - 1); /* don't copy the final `)' */
2350 token[ttoklen] = '"';
2351 token[ttoklen+1] = '\0';
2355 token[ttoklen] = ')';
2356 token[ttoklen+1] = c;
2357 token[ttoklen+2] = '\0';
2363 #endif /* DPAREN_ARITHMETIC */
2366 read_token_word (character)
2369 /* The value for YYLVAL when a WORD is read. */
2370 WORD_DESC *the_word;
2372 /* Index into the token that we are building. */
2375 /* ALL_DIGITS becomes zero when we see a non-digit. */
2378 /* DOLLAR_PRESENT becomes non-zero if we see a `$'. */
2381 /* QUOTED becomes non-zero if we see one of ("), ('), (`), or (\). */
2384 /* Non-zero means to ignore the value of the next character, and just
2385 to add it no matter what. */
2386 int pass_next_character;
2388 /* The current delimiting character. */
2390 int result, peek_char;
2391 char *ttok, *ttrans;
2392 int ttoklen, ttranslen;
2394 if (token_buffer_size < TOKEN_DEFAULT_INITIAL_SIZE)
2395 token = xrealloc (token, token_buffer_size = TOKEN_DEFAULT_INITIAL_SIZE);
2398 all_digits = digit (character);
2399 dollar_present = quoted = pass_next_character = 0;
2403 if (character == EOF)
2406 if (pass_next_character)
2408 pass_next_character = 0;
2412 cd = current_delimiter (dstack);
2414 /* Handle backslashes. Quote lots of things when not inside of
2415 double-quotes, quote some things inside of double-quotes. */
2416 if (character == '\\')
2418 peek_char = shell_getc (0);
2420 /* Backslash-newline is ignored in all cases except
2421 when quoted with single quotes. */
2422 if (peek_char == '\n')
2425 goto next_character;
2429 shell_ungetc (peek_char);
2431 /* If the next character is to be quoted, note it now. */
2432 if (cd == 0 || cd == '`' ||
2433 (cd == '"' && member (peek_char, slashify_in_quotes)))
2434 pass_next_character++;
2441 /* Parse a matched pair of quote characters. */
2442 if (shellquote (character))
2444 push_delimiter (dstack, character);
2445 ttok = parse_matched_pair (character, character, character, &ttoklen, 0);
2446 pop_delimiter (dstack);
2447 if (ttok == &matched_pair_error)
2448 return -1; /* Bail immediately. */
2449 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
2450 token_buffer_size, TOKEN_DEFAULT_GROW_SIZE);
2451 token[token_index++] = character;
2452 strcpy (token + token_index, ttok);
2453 token_index += ttoklen;
2456 dollar_present |= (character == '"' && strchr (ttok, '$') != 0);
2458 goto next_character;
2461 /* If the delimiter character is not single quote, parse some of
2462 the shell expansions that must be read as a single word. */
2463 #if defined (PROCESS_SUBSTITUTION)
2464 if (character == '$' || character == '<' || character == '>')
2466 if (character == '$')
2467 #endif /* !PROCESS_SUBSTITUTION */
2469 peek_char = shell_getc (1);
2470 /* $(...), <(...), >(...), $((...)), ${...}, and $[...] constructs */
2471 if (peek_char == '(' ||
2472 ((peek_char == '{' || peek_char == '[') && character == '$')) /* ) ] } */
2474 if (peek_char == '{') /* } */
2475 ttok = parse_matched_pair (cd, '{', '}', &ttoklen, 0);
2476 else if (peek_char == '(') /* ) */
2478 /* XXX - push and pop the `(' as a delimiter for use by
2479 the command-oriented-history code. This way newlines
2480 appearing in the $(...) string get added to the
2481 history literally rather than causing a possibly-
2482 incorrect `;' to be added. */
2483 push_delimiter (dstack, peek_char);
2484 ttok = parse_matched_pair (cd, '(', ')', &ttoklen, 0);
2485 pop_delimiter (dstack);
2488 ttok = parse_matched_pair (cd, '[', ']', &ttoklen, 0);
2489 if (ttok == &matched_pair_error)
2490 return -1; /* Bail immediately. */
2491 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
2493 TOKEN_DEFAULT_GROW_SIZE);
2494 token[token_index++] = character;
2495 token[token_index++] = peek_char;
2496 strcpy (token + token_index, ttok);
2497 token_index += ttoklen;
2501 goto next_character;
2503 /* This handles $'...' and $"..." new-style quoted strings. */
2504 else if (character == '$' && (peek_char == '\'' || peek_char == '"'))
2506 ttok = parse_matched_pair (peek_char, peek_char, peek_char, &ttoklen, 0);
2507 if (ttok == &matched_pair_error)
2509 if (peek_char == '\'')
2510 ttrans = ansiexpand (ttok, 0, ttoklen - 1, &ttranslen);
2512 ttrans = localeexpand (ttok, 0, ttoklen - 1, &ttranslen);
2514 RESIZE_MALLOCED_BUFFER (token, token_index, ttranslen + 2,
2516 TOKEN_DEFAULT_GROW_SIZE);
2517 token[token_index++] = peek_char;
2518 strcpy (token + token_index, ttrans);
2519 token_index += ttranslen;
2520 token[token_index++] = peek_char;
2524 goto next_character;
2527 shell_ungetc (peek_char);
2530 #if defined (ARRAY_VARS)
2531 /* Identify possible compound array variable assignment. */
2532 else if (character == '=' && token_index > 0)
2534 peek_char = shell_getc (1);
2535 if (peek_char == '(') /* ) */
2537 ttok = parse_matched_pair (cd, '(', ')', &ttoklen, 0);
2538 if (ttok == &matched_pair_error)
2539 return -1; /* Bail immediately. */
2540 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
2542 TOKEN_DEFAULT_GROW_SIZE);
2543 token[token_index++] = character;
2544 token[token_index++] = peek_char;
2545 strcpy (token + token_index, ttok);
2546 token_index += ttoklen;
2549 goto next_character;
2552 shell_ungetc (peek_char);
2556 /* When not parsing a multi-character word construct, shell meta-
2557 characters break words. */
2558 if (shellbreak (character))
2560 shell_ungetc (character);
2566 all_digits &= digit (character);
2567 dollar_present |= character == '$';
2569 if (character == CTLESC || character == CTLNUL)
2570 token[token_index++] = CTLESC;
2572 token[token_index++] = character;
2574 RESIZE_MALLOCED_BUFFER (token, token_index, 1, token_buffer_size,
2575 TOKEN_DEFAULT_GROW_SIZE);
2578 if (character == '\n' && interactive &&
2579 (bash_input.type == st_stdin || bash_input.type == st_stream))
2582 /* We want to remove quoted newlines (that is, a \<newline> pair)
2583 unless we are within single quotes or pass_next_character is
2584 set (the shell equivalent of literal-next). */
2585 cd = current_delimiter (dstack);
2586 character = shell_getc (cd != '\'' && pass_next_character == 0);
2587 } /* end for (;;) */
2591 token[token_index] = '\0';
2593 /* Check to see what thing we should return. If the last_read_token
2594 is a `<', or a `&', or the character which ended this token is
2595 a '>' or '<', then, and ONLY then, is this input token a NUMBER.
2596 Otherwise, it is just a word, and should be returned as such. */
2597 if (all_digits && (character == '<' || character == '>' ||
2598 last_read_token == LESS_AND ||
2599 last_read_token == GREATER_AND))
2601 yylval.number = atoi (token);
2605 /* Check for special case tokens. */
2606 result = special_case_tokens (token);
2611 /* Posix.2 does not allow reserved words to be aliased, so check for all
2612 of them, including special cases, before expanding the current token
2614 if (posixly_correct)
2615 CHECK_FOR_RESERVED_WORD (token);
2617 /* Aliases are expanded iff EXPAND_ALIASES is non-zero, and quoting
2618 inhibits alias expansion. */
2619 if (expand_aliases && quoted == 0)
2621 result = alias_expand_token (token);
2622 if (result == RE_READ_TOKEN)
2623 return (RE_READ_TOKEN);
2624 else if (result == NO_EXPANSION)
2625 parser_state &= ~PST_ALEXPNEXT;
2628 /* If not in Posix.2 mode, check for reserved words after alias
2630 if (posixly_correct == 0)
2632 CHECK_FOR_RESERVED_WORD (token);
2634 the_word = (WORD_DESC *)xmalloc (sizeof (WORD_DESC));
2635 the_word->word = xmalloc (1 + token_index);
2636 the_word->flags = 0;
2637 strcpy (the_word->word, token);
2639 the_word->flags |= W_HASDOLLAR;
2641 the_word->flags |= W_QUOTED;
2642 /* A word is an assignment if it appears at the beginning of a
2643 simple command, or after another assignment word. This is
2644 context-dependent, so it cannot be handled in the grammar. */
2645 if (assignment (token))
2647 the_word->flags |= W_ASSIGNMENT;
2648 /* Don't perform word splitting on assignment statements. */
2649 if (assignment_acceptable (last_read_token))
2650 the_word->flags |= W_NOSPLIT;
2653 yylval.word = the_word;
2655 result = ((the_word->flags & (W_ASSIGNMENT|W_NOSPLIT)) == (W_ASSIGNMENT|W_NOSPLIT))
2656 ? ASSIGNMENT_WORD : WORD;
2658 if (last_read_token == FUNCTION)
2660 parser_state |= PST_ALLOWOPNBRC;
2661 function_dstart = line_number;
2667 /* $'...' ANSI-C expand the portion of STRING between START and END and
2668 return the result. The result cannot be longer than the input string. */
2670 ansiexpand (string, start, end, lenp)
2672 int start, end, *lenp;
2677 temp = xmalloc (end - start + 1);
2678 for (tlen = 0, len = start; len < end; )
2679 temp[tlen++] = string[len++];
2684 t = ansicstr (temp, tlen, (int *)NULL, lenp);
2696 /* $"..." -- Translate the portion of STRING between START and END
2697 according to current locale using gettext (if available) and return
2698 the result. The caller will take care of leaving the quotes intact.
2699 The string will be left without the leading `$' by the caller.
2700 If translation is performed, the translated string will be double-quoted
2701 by the caller. The length of the translated string is returned in LENP,
2704 localeexpand (string, start, end, lenp)
2706 int start, end, *lenp;
2711 temp = xmalloc (end - start + 1);
2712 for (tlen = 0, len = start; len < end; )
2713 temp[tlen++] = string[len++];
2716 /* If we're just dumping translatable strings, don't do anything. */
2717 if (dump_translatable_strings)
2719 printf ("\"%s\"\n", temp);
2726 t = localetrans (temp, tlen, &len);
2740 /* Return 1 if TOKEN is a token that after being read would allow
2741 a reserved word to be seen, else 0. */
2743 reserved_word_acceptable (token)
2746 if (token == '\n' || token == ';' || token == '(' || token == ')' ||
2747 token == '|' || token == '&' || token == '{' ||
2748 token == '}' || /* XXX */
2751 token == TIME || token == TIMEOPT ||
2758 token == SEMI_SEMI ||
2762 token == DONE || /* XXX these two are experimental */
2770 /* Return the index of TOKEN in the alist of reserved words, or -1 if
2771 TOKEN is not a shell reserved word. */
2773 find_reserved_word (token)
2777 for (i = 0; word_token_alist[i].word; i++)
2778 if (STREQ (token, word_token_alist[i].word))
2784 #if defined (READLINE)
2785 /* Called after each time readline is called. This insures that whatever
2786 the new prompt string is gets propagated to readline's local prompt
2789 reset_readline_prompt ()
2793 if (prompt_string_pointer)
2795 temp_prompt = (*prompt_string_pointer)
2796 ? decode_prompt_string (*prompt_string_pointer)
2799 if (temp_prompt == 0)
2801 temp_prompt = xmalloc (1);
2802 temp_prompt[0] = '\0';
2805 FREE (current_readline_prompt);
2806 current_readline_prompt = temp_prompt;
2809 #endif /* READLINE */
2812 #if defined (HISTORY)
2813 /* A list of tokens which can be followed by newlines, but not by
2814 semi-colons. When concatenating multiple lines of history, the
2815 newline separator for such tokens is replaced with a space. */
2816 static int no_semi_successors[] = {
2817 '\n', '{', '(', ')', ';', '&', '|',
2818 CASE, DO, ELSE, IF, SEMI_SEMI, THEN, UNTIL, WHILE, AND_AND, OR_OR, IN,
2822 /* If we are not within a delimited expression, try to be smart
2823 about which separators can be semi-colons and which must be
2824 newlines. Returns the string that should be added into the
2827 history_delimiting_chars ()
2831 if (dstack.delimiter_depth != 0)
2834 /* First, handle some special cases. */
2836 /* If we just read `()', assume it's a function definition, and don't
2837 add a semicolon. If the token before the `)' was not `(', and we're
2838 not in the midst of parsing a case statement, assume it's a
2839 parenthesized command and add the semicolon. */
2841 if (token_before_that == ')')
2843 if (two_tokens_ago == '(') /*)*/ /* function def */
2845 /* This does not work for subshells inside case statement
2846 command lists. It's a suboptimal solution. */
2847 else if (parser_state & PST_CASESTMT) /* case statement pattern */
2850 return "; "; /* (...) subshell */
2853 for (i = 0; no_semi_successors[i]; i++)
2855 if (token_before_that == no_semi_successors[i])
2861 #endif /* HISTORY */
2863 /* Issue a prompt, or prepare to issue a prompt when the next character
2870 if (!interactive) /* XXX */
2873 ps1_prompt = get_string_value ("PS1");
2874 ps2_prompt = get_string_value ("PS2");
2876 if (!prompt_string_pointer)
2877 prompt_string_pointer = &ps1_prompt;
2879 temp_prompt = *prompt_string_pointer
2880 ? decode_prompt_string (*prompt_string_pointer)
2883 if (temp_prompt == 0)
2885 temp_prompt = xmalloc (1);
2886 temp_prompt[0] = '\0';
2889 current_prompt_string = *prompt_string_pointer;
2890 prompt_string_pointer = &ps2_prompt;
2892 #if defined (READLINE)
2893 if (!no_line_editing)
2895 FREE (current_readline_prompt);
2896 current_readline_prompt = temp_prompt;
2899 #endif /* READLINE */
2901 FREE (current_decoded_prompt);
2902 current_decoded_prompt = temp_prompt;
2909 fprintf (stderr, "%s", current_decoded_prompt);
2913 /* Return a string which will be printed as a prompt. The string
2914 may contain special characters which are decoded as follows:
2917 \e escape (ascii 033)
2918 \d the date in Day Mon Date format
2919 \h the hostname up to the first `.'
2922 \s the name of the shell
2923 \t the time in 24-hour hh:mm:ss format
2924 \T the time in 12-hour hh:mm:ss format
2925 \@ the time in 12-hour am/pm format
2926 \v the version of bash (e.g., 2.00)
2927 \V the release of bash, version + patchlevel (e.g., 2.00.0)
2928 \w the current working directory
2929 \W the last element of $PWD
2931 \# the command number of this command
2932 \! the history number of this command
2933 \$ a $ or a # if you are root
2934 \nnn character code nnn in octal
2936 \[ begin a sequence of non-printing chars
2937 \] end a sequence of non-printing chars
2939 #define PROMPT_GROWTH 48
2941 decode_prompt_string (string)
2946 struct dstack save_dstack;
2947 #if defined (PROMPT_STRING_DECODE)
2948 int result_size, result_index;
2950 char *temp, octal_string[4];
2953 result = xmalloc (result_size = PROMPT_GROWTH);
2954 result[result_index = 0] = 0;
2955 temp = (char *)NULL;
2957 while (c = *string++)
2959 if (posixly_correct && c == '!')
2963 temp = savestring ("!");
2968 #if !defined (HISTORY)
2969 temp = savestring ("1");
2971 temp = itos (history_number ());
2972 #endif /* HISTORY */
2973 string--; /* add_string increments string again. */
2991 strncpy (octal_string, string, 3);
2992 octal_string[3] = '\0';
2994 n = read_octal (octal_string);
2997 if (n == CTLESC || n == CTLNUL)
3023 /* Make the current time/date into a string. */
3024 the_time = time (0);
3025 temp = ctime (&the_time);
3027 temp = (c != 'd') ? savestring (temp + 11) : savestring (temp);
3028 temp[(c != 'd') ? 8 : 10] = '\0';
3030 /* quick and dirty conversion to 12-hour time */
3031 if (c == 'T' || c == '@')
3035 temp[5] = 'a'; /* am/pm format */
3046 temp[0] = (n / 10) + '0';
3047 temp[1] = (n % 10) + '0';
3049 if (n >= 0 && temp[5] == 'a')
3056 temp[0] = no_line_editing ? '\n' : '\r';
3057 temp[1] = no_line_editing ? '\0' : '\n';
3062 temp = base_pathname (shell_name);
3063 temp = savestring (temp);
3070 strcpy (temp, dist_version);
3072 sprintf (temp, "%s.%d", dist_version, patch_level);
3078 /* Use the value of PWD because it is much more efficient. */
3079 char t_string[PATH_MAX];
3082 temp = get_string_value ("PWD");
3086 if (getcwd (t_string, sizeof(t_string)) == 0)
3092 tlen = strlen (t_string);
3096 tlen = sizeof (t_string) - 1;
3097 strncpy (t_string, temp, tlen);
3099 t_string[tlen] = '\0';
3103 t = strrchr (t_string, '/');
3104 if (t && t != t_string)
3105 strcpy (t_string, t + 1);
3108 /* polite_directory_format is guaranteed to return a string
3109 no longer than PATH_MAX - 1 characters. */
3110 strcpy (t_string, polite_directory_format (t_string));
3112 /* If we're going to be expanding the prompt string later,
3113 quote the directory name. */
3114 if (promptvars || posixly_correct)
3115 temp = backslash_quote (t_string);
3117 temp = savestring (t_string);
3123 temp = savestring (current_user.user_name);
3128 temp = savestring (current_host_name);
3129 if (c == 'h' && (t = (char *)strchr (temp, '.')))
3134 temp = itos (current_command_number);
3138 #if !defined (HISTORY)
3139 temp = savestring ("1");
3141 temp = itos (history_number ());
3142 #endif /* HISTORY */
3147 temp[0] = current_user.euid == 0 ? '#' : '$';
3151 #if defined (READLINE)
3156 temp[1] = (c == '[') ? RL_PROMPT_START_IGNORE : RL_PROMPT_END_IGNORE;
3159 #endif /* READLINE */
3170 temp[0] = (c == 'a') ? '\07' : '\033';
3184 sub_append_string (temp, result, &result_index, &result_size);
3185 temp = (char *)NULL; /* Freed in sub_append_string (). */
3186 result[result_index] = '\0';
3192 RESIZE_MALLOCED_BUFFER (result, result_index, 3, result_size, PROMPT_GROWTH);
3193 result[result_index++] = c;
3194 result[result_index] = '\0';
3197 #else /* !PROMPT_STRING_DECODE */
3198 result = savestring (string);
3199 #endif /* !PROMPT_STRING_DECODE */
3201 /* Save the delimiter stack and point `dstack' to temp space so any
3202 command substitutions in the prompt string won't result in screwing
3203 up the parser's quoting state. */
3204 save_dstack = dstack;
3205 dstack = temp_dstack;
3206 dstack.delimiter_depth = 0;
3208 /* Perform variable and parameter expansion and command substitution on
3209 the prompt string. */
3210 if (promptvars || posixly_correct)
3212 list = expand_string_unsplit (result, Q_DOUBLE_QUOTES);
3214 result = string_list (list);
3215 dispose_words (list);
3219 t = dequote_string (result);
3224 dstack = save_dstack;
3229 /* Report a syntax error, and restart the parser. Call here for fatal
3234 report_syntax_error ((char *)NULL);
3239 /* Report a syntax error with line numbers, etc.
3240 Call here for recoverable errors. If you have a message to print,
3241 then place it in MESSAGE, otherwise pass NULL and this will figure
3242 out an appropriate message for you. */
3244 report_syntax_error (message)
3253 parser_error (line_number, "%s", message);
3254 if (interactive && EOF_Reached)
3256 last_command_exit_value = EX_USAGE;
3260 /* If the line of input we're reading is not null, try to find the
3261 objectionable token. */
3262 if (shell_input_line && *shell_input_line)
3264 t = shell_input_line;
3265 i = shell_input_line_index;
3268 if (i && t[i] == '\0')
3271 while (i && (whitespace (t[i]) || t[i] == '\n'))
3277 while (i && (member (t[i], " \n\t;|&") == 0))
3280 while (i != token_end && (whitespace (t[i]) || t[i] == '\n'))
3283 /* Print the offending token. */
3284 if (token_end || (i == 0 && token_end == 0))
3288 msg = xmalloc (1 + (token_end - i));
3289 strncpy (msg, t + i, token_end - i);
3290 msg[token_end - i] = '\0';
3292 else /* one-character token */
3299 parser_error (line_number, "syntax error near unexpected token `%s'", msg);
3305 /* If not interactive, print the line containing the error. */
3306 if (interactive == 0)
3308 msg = savestring (shell_input_line);
3309 token_end = strlen (msg);
3310 while (token_end && msg[token_end - 1] == '\n')
3311 msg[--token_end] = '\0';
3313 parser_error (line_number, "`%s'", msg);
3319 msg = EOF_Reached ? "syntax error: unexpected end of file" : "syntax error";
3320 parser_error (line_number, "%s", msg);
3321 /* When the shell is interactive, this file uses EOF_Reached
3322 only for error reporting. Other mechanisms are used to
3323 decide whether or not to exit. */
3324 if (interactive && EOF_Reached)
3327 last_command_exit_value = EX_USAGE;
3330 /* ??? Needed function. ??? We have to be able to discard the constructs
3331 created during parsing. In the case of error, we want to return
3332 allocated objects to the memory pool. In the case of no error, we want
3333 to throw away the information about where the allocated objects live.
3334 (dispose_command () will actually free the command. */
3336 discard_parser_constructs (error_p)
3341 /* Do that silly `type "bye" to exit' stuff. You know, "ignoreeof". */
3343 /* A flag denoting whether or not ignoreeof is set. */
3346 /* The number of times that we have encountered an EOF character without
3347 another character intervening. When this gets above the limit, the
3348 shell terminates. */
3349 int eof_encountered = 0;
3351 /* The limit for eof_encountered. */
3352 int eof_encountered_limit = 10;
3354 /* If we have EOF as the only input unit, this user wants to leave
3355 the shell. If the shell is not interactive, then just leave.
3356 Otherwise, if ignoreeof is set, and we haven't done this the
3357 required number of times in a row, print a message. */
3359 handle_eof_input_unit ()
3363 /* shell.c may use this to decide whether or not to write out the
3364 history, among other things. We use it only for error reporting
3369 /* If the user wants to "ignore" eof, then let her do so, kind of. */
3372 if (eof_encountered < eof_encountered_limit)
3374 fprintf (stderr, "Use \"%s\" to leave the shell.\n",
3375 login_shell ? "logout" : "exit");
3377 /* Reset the prompt string to be $PS1. */
3378 prompt_string_pointer = (char **)NULL;
3380 last_read_token = current_token = '\n';
3385 /* In this case EOF should exit the shell. Do it now. */
3387 exit_builtin ((WORD_LIST *)NULL);
3391 /* We don't write history files, etc., for non-interactive shells. */