1 /* arrayfunc.c -- High-level array functions used by other parts of the shell. */
3 /* Copyright (C) 2001-2002 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
12 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License along
18 with Bash; see the file COPYING. If not, write to the Free Software
19 Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
23 #if defined (ARRAY_VARS)
25 #if defined (HAVE_UNISTD_H)
34 #include "builtins/common.h"
36 extern char *this_command_name;
37 extern int last_command_exit_value;
39 static void quote_array_assignment_chars __P((WORD_LIST *));
40 static char *array_value_internal __P((char *, int, int, int *));
42 /* **************************************************************** */
44 /* Functions to manipulate array variables and perform assignments */
46 /* **************************************************************** */
48 /* Convert a shell variable to an array variable. The original value is
51 convert_var_to_array (var)
57 oldval = value_cell (var);
58 array = array_create ();
59 array_insert (array, 0, oldval);
61 FREE (value_cell (var));
62 var_setarray (var, array);
64 /* these aren't valid anymore */
65 var->dynamic_value = (sh_var_value_func_t *)NULL;
66 var->assign_func = (sh_var_assign_func_t *)NULL;
68 INVALIDATE_EXPORTSTR (var);
70 VSETATTR (var, att_array);
71 VUNSETATTR (var, att_invisible);
76 /* Perform an array assignment name[ind]=value. If NAME already exists and
77 is not an array, and IND is 0, perform name=value instead. If NAME exists
78 and is not an array, and IND is not 0, convert it into an array with the
79 existing value as name[0].
81 If NAME does not exist, just create an array variable, no matter what
82 IND's value may be. */
84 bind_array_variable (name, ind, value)
92 entry = var_lookup (name, shell_variables);
94 if (entry == (SHELL_VAR *) 0)
95 entry = make_new_array_variable (name);
96 else if (readonly_p (entry) || noassign_p (entry))
98 if (readonly_p (entry))
102 else if (array_p (entry) == 0)
103 entry = convert_var_to_array (entry);
105 /* ENTRY is an array variable, and ARRAY points to the value. */
106 newval = make_variable_value (entry, value);
107 if (entry->assign_func)
108 (*entry->assign_func) (entry, newval, ind);
110 array_insert (array_cell (entry), ind, newval);
116 /* Parse NAME, a lhs of an assignment statement of the form v[s], and
117 assign VALUE to that array element by calling bind_array_variable(). */
119 assign_array_element (name, value)
127 vname = array_variable_name (name, &sub, &sublen);
130 return ((SHELL_VAR *)NULL);
132 if ((ALL_ELEMENT_SUB (sub[0]) && sub[1] == ']') || (sublen <= 1))
135 err_badarraysub (name);
136 return ((SHELL_VAR *)NULL);
139 ind = array_expand_index (sub, sublen);
143 err_badarraysub (name);
144 return ((SHELL_VAR *)NULL);
147 entry = bind_array_variable (vname, ind, value);
153 /* Find the array variable corresponding to NAME. If there is no variable,
154 create a new array variable. If the variable exists but is not an array,
155 convert it to an indexed array. If CHECK_FLAGS is non-zero, an existing
156 variable is checked for the readonly or noassign attribute in preparation
157 for assignment (e.g., by the `read' builtin). */
159 find_or_make_array_variable (name, check_flags)
165 var = find_variable (name);
168 var = make_new_array_variable (name);
169 else if (check_flags && (readonly_p (var) || noassign_p (var)))
171 if (readonly_p (var))
173 return ((SHELL_VAR *)NULL);
175 else if (array_p (var) == 0)
176 var = convert_var_to_array (var);
181 /* Perform a compound assignment statement for array NAME, where VALUE is
182 the text between the parens: NAME=( VALUE ) */
184 assign_array_from_string (name, value)
189 var = find_or_make_array_variable (name, 1);
191 return ((SHELL_VAR *)NULL);
193 return (assign_array_var_from_string (var, value));
196 /* Sequentially assign the indices of indexed array variable VAR from the
199 assign_array_var_from_word_list (var, list)
203 register arrayind_t i;
204 register WORD_LIST *l;
207 for (a = array_cell (var), l = list, i = 0; l; l = l->next, i++)
208 if (var->assign_func)
209 (*var->assign_func) (var, l->word->word, i);
211 array_insert (a, i, l->word->word);
215 /* Perform a compound array assignment: VAR->name=( VALUE ). The
216 VALUE has already had the parentheses stripped. */
218 assign_array_var_from_string (var, value)
223 WORD_LIST *list, *nlist;
224 char *w, *val, *nval;
226 arrayind_t ind, last_ind;
231 /* If this is called from declare_builtin, value[0] == '(' and
232 xstrchr(value, ')') != 0. In this case, we need to extract
233 the value from between the parens before going on. */
234 if (*value == '(') /*)*/
237 val = extract_array_assignment_list (value, &ni);
244 /* Expand the value string into a list of words, performing all the
245 shell expansions including pathname generation and word splitting. */
246 /* First we split the string on whitespace, using the shell parser
247 (ksh93 seems to do this). */
248 list = parse_string_to_word_list (val, "array assign");
250 /* If we're using [subscript]=value, we need to quote each [ and ] to
251 prevent unwanted filename expansion. */
253 quote_array_assignment_chars (list);
255 /* Now that we've split it, perform the shell expansions on each
257 nlist = list ? expand_words_no_vars (list) : (WORD_LIST *)NULL;
259 dispose_words (list);
264 a = array_cell (var);
266 /* Now that we are ready to assign values to the array, kill the existing
271 for (last_ind = 0, list = nlist; list; list = list->next)
273 w = list->word->word;
275 /* We have a word of the form [ind]=value */
278 len = skipsubscript (w, 0);
280 if (w[len] != ']' || w[len+1] != '=')
282 nval = make_variable_value (var, w);
283 if (var->assign_func)
284 (*var->assign_func) (var, nval, last_ind);
286 array_insert (a, last_ind, nval);
298 if (ALL_ELEMENT_SUB (w[1]) && len == 2)
300 report_error ("%s: cannot assign to non-numeric index", w);
304 ind = array_expand_index (w + 1, len);
313 else /* No [ind]=value, just a stray `=' */
320 this_command_name = (char *)NULL; /* no command name for errors */
321 nval = make_variable_value (var, val);
322 if (var->assign_func)
323 (*var->assign_func) (var, nval, ind);
325 array_insert (a, ind, nval);
330 dispose_words (nlist);
334 /* For each word in a compound array assignment, if the word looks like
335 [ind]=value, quote the `[' and `]' before the `=' to protect them from
336 unwanted filename expansion. */
338 quote_array_assignment_chars (list)
345 for (l = list; l; l = l->next)
347 if (l->word == 0 || l->word->word == 0 || l->word->word[0] == '\0')
348 continue; /* should not happen, but just in case... */
349 /* Don't bother if it doesn't look like [ind]=value */
350 if (l->word->word[0] != '[' || xstrchr (l->word->word, '=') == 0) /* ] */
352 s = nword = (char *)xmalloc (strlen (l->word->word) * 2 + 1);
354 for (t = l->word->word; *t; )
358 if (saw_eq == 0 && (*t == '[' || *t == ']'))
363 free (l->word->word);
364 l->word->word = nword;
368 /* This function assumes s[i] == '['; returns with s[ret] == ']' if
369 an array subscript is correctly parsed. */
376 #if defined (HANDLE_MULTIBYTE)
377 mbstate_t state, state_bak;
378 size_t slength, mblength;
382 #if defined (HANDLE_MULTIBYTE)
383 memset (&state, '\0', sizeof (mbstate_t));
384 slength = strlen (s + i);
385 mb_cur_max = MB_CUR_MAX;
391 /* Advance one (possibly multibyte) character in S starting at I. */
392 #if defined (HANDLE_MULTIBYTE)
396 mblength = mbrlen (s + i, slength, &state);
398 if (mblength == (size_t)-2 || mblength == (size_t)-1)
404 else if (mblength == 0)
429 /* This function is called with SUB pointing to just after the beginning
430 `[' of an array subscript and removes the array element to which SUB
431 expands from array VAR. A subscript of `*' or `@' unsets the array. */
433 unbind_array_element (var, sub)
441 len = skipsubscript (sub, 0);
442 if (sub[len] != ']' || len == 0)
444 builtin_error ("%s[%s: bad array subscript", var->name, sub);
449 if (ALL_ELEMENT_SUB (sub[0]) && sub[1] == 0)
451 unbind_variable (var->name);
454 ind = array_expand_index (sub, len+1);
457 builtin_error ("[%s]: bad array subscript", sub);
460 ae = array_remove (array_cell (var), ind);
462 array_dispose_element (ae);
466 /* Format and output an array assignment in compound form VAR=(VALUES),
467 suitable for re-use as input. */
469 print_array_assignment (var, quoted)
475 vstr = array_to_assign (array_cell (var), quoted);
478 printf ("%s=%s\n", var->name, quoted ? "'()'" : "()");
481 printf ("%s=%s\n", var->name, vstr);
486 /***********************************************************************/
488 /* Utility functions to manage arrays and their contents for expansion */
490 /***********************************************************************/
492 /* Return 1 if NAME is a properly-formed array reference v[sub]. */
494 valid_array_reference (name)
500 t = xstrchr (name, '['); /* ] */
504 r = legal_identifier (name);
508 /* Check for a properly-terminated non-blank subscript. */
509 len = skipsubscript (t, 0);
510 if (t[len] != ']' || len == 1)
512 for (r = 1; r < len; r++)
513 if (whitespace (t[r]) == 0)
520 /* Expand the array index beginning at S and extending LEN characters. */
522 array_expand_index (s, len)
530 exp = (char *)xmalloc (len);
531 strncpy (exp, s, len - 1);
533 t = expand_string_to_string (exp, 0);
534 this_command_name = (char *)NULL;
535 val = evalexp (t, &expok);
540 last_command_exit_value = EXECUTION_FAILURE;
541 jump_to_top_level (DISCARD);
546 /* Return the name of the variable specified by S without any subscript.
547 If SUBP is non-null, return a pointer to the start of the subscript
548 in *SUBP. If LENP is non-null, the length of the subscript is returned
549 in *LENP. This returns newly-allocated memory. */
551 array_variable_name (s, subp, lenp)
558 t = xstrchr (s, '[');
560 return ((char *)NULL);
562 ni = skipsubscript (s, ind);
563 if (ni <= ind + 1 || s[ni] != ']')
566 return ((char *)NULL);
570 ret = savestring (s);
581 /* Return the variable specified by S without any subscript. If SUBP is
582 non-null, return a pointer to the start of the subscript in *SUBP.
583 If LENP is non-null, the length of the subscript is returned in *LENP. */
585 array_variable_part (s, subp, lenp)
592 t = array_variable_name (s, subp, lenp);
594 return ((SHELL_VAR *)NULL);
595 var = find_variable (t);
601 /* Return a string containing the elements in the array and subscript
602 described by S. If the subscript is * or @, obeys quoting rules akin
603 to the expansion of $* and $@ including double quoting. If RTYPE
604 is non-null it gets 1 if the array reference is name[@] or name[*]
607 array_value_internal (s, quoted, allow_all, rtype)
609 int quoted, allow_all, *rtype;
613 char *retval, *t, *temp;
617 var = array_variable_part (s, &t, &len);
619 /* Expand the index, even if the variable doesn't exist, in case side
620 effects are needed, like ${w[i++]} where w is unset. */
627 if (ALL_ELEMENT_SUB (t[0]) && t[1] == ']')
634 return ((char *)NULL);
637 return ((char *)NULL);
638 else if (array_p (var) == 0)
639 l = add_string_to_list (value_cell (var), (WORD_LIST *)NULL);
642 l = array_to_word_list (array_cell (var));
643 if (l == (WORD_LIST *)NULL)
644 return ((char *) NULL);
647 if (t[0] == '*' && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
649 temp = string_list_dollar_star (l);
650 retval = quote_string (temp);
653 else /* ${name[@]} or unquoted ${name[*]} */
654 retval = string_list_dollar_at (l, quoted);
662 ind = array_expand_index (t, len);
666 err_badarraysub (var->name);
673 return ((char *)NULL);
676 return ((char *)NULL);
677 if (array_p (var) == 0)
678 return (ind == 0 ? value_cell (var) : (char *)NULL);
679 retval = array_reference (array_cell (var), ind);
685 /* Return a string containing the elements described by the array and
686 subscript contained in S, obeying quoting for subscripts * and @. */
688 array_value (s, quoted, rtype)
692 return (array_value_internal (s, quoted, 1, rtype));
695 /* Return the value of the array indexing expression S as a single string.
696 If ALLOW_ALL is 0, do not allow `@' and `*' subscripts. This is used
697 by other parts of the shell such as the arithmetic expression evaluator
700 get_array_value (s, allow_all, rtype)
702 int allow_all, *rtype;
704 return (array_value_internal (s, 0, allow_all, rtype));
707 #endif /* ARRAY_VARS */