1 /* arrayfunc.c -- High-level array functions used by other parts of the shell. */
3 /* Copyright (C) 2001-2003 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)
36 #include "builtins/common.h"
38 extern char *this_command_name
;
39 extern int last_command_exit_value
;
41 static void quote_array_assignment_chars
__P((WORD_LIST
*));
42 static char *array_value_internal
__P((char *, int, int, int *));
44 /* Standard error message to use when encountering an invalid array subscript */
45 char *bash_badsub_errmsg
= N_("bad array subscript");
47 /* **************************************************************** */
49 /* Functions to manipulate array variables and perform assignments */
51 /* **************************************************************** */
53 /* Convert a shell variable to an array variable. The original value is
56 convert_var_to_array (var
)
62 oldval
= value_cell (var
);
63 array
= array_create ();
65 array_insert (array
, 0, oldval
);
67 FREE (value_cell (var
));
68 var_setarray (var
, array
);
70 /* these aren't valid anymore */
71 var
->dynamic_value
= (sh_var_value_func_t
*)NULL
;
72 var
->assign_func
= (sh_var_assign_func_t
*)NULL
;
74 INVALIDATE_EXPORTSTR (var
);
76 VSETATTR (var
, att_array
);
77 VUNSETATTR (var
, att_invisible
);
82 /* Perform an array assignment name[ind]=value. If NAME already exists and
83 is not an array, and IND is 0, perform name=value instead. If NAME exists
84 and is not an array, and IND is not 0, convert it into an array with the
85 existing value as name[0].
87 If NAME does not exist, just create an array variable, no matter what
88 IND's value may be. */
90 bind_array_variable (name
, ind
, value
)
98 entry
= var_lookup (name
, shell_variables
);
100 if (entry
== (SHELL_VAR
*) 0)
101 entry
= make_new_array_variable (name
);
102 else if (readonly_p (entry
) || noassign_p (entry
))
104 if (readonly_p (entry
))
108 else if (array_p (entry
) == 0)
109 entry
= convert_var_to_array (entry
);
111 /* ENTRY is an array variable, and ARRAY points to the value. */
112 newval
= make_variable_value (entry
, value
);
113 if (entry
->assign_func
)
114 (*entry
->assign_func
) (entry
, newval
, ind
);
116 array_insert (array_cell (entry
), ind
, newval
);
122 /* Parse NAME, a lhs of an assignment statement of the form v[s], and
123 assign VALUE to that array element by calling bind_array_variable(). */
125 assign_array_element (name
, value
)
133 vname
= array_variable_name (name
, &sub
, &sublen
);
136 return ((SHELL_VAR
*)NULL
);
138 if ((ALL_ELEMENT_SUB (sub
[0]) && sub
[1] == ']') || (sublen
<= 1))
141 err_badarraysub (name
);
142 return ((SHELL_VAR
*)NULL
);
145 ind
= array_expand_index (sub
, sublen
);
149 err_badarraysub (name
);
150 return ((SHELL_VAR
*)NULL
);
153 entry
= bind_array_variable (vname
, ind
, value
);
159 /* Find the array variable corresponding to NAME. If there is no variable,
160 create a new array variable. If the variable exists but is not an array,
161 convert it to an indexed array. If CHECK_FLAGS is non-zero, an existing
162 variable is checked for the readonly or noassign attribute in preparation
163 for assignment (e.g., by the `read' builtin). */
165 find_or_make_array_variable (name
, check_flags
)
171 var
= find_variable (name
);
174 var
= make_new_array_variable (name
);
175 else if (check_flags
&& (readonly_p (var
) || noassign_p (var
)))
177 if (readonly_p (var
))
179 return ((SHELL_VAR
*)NULL
);
181 else if (array_p (var
) == 0)
182 var
= convert_var_to_array (var
);
187 /* Perform a compound assignment statement for array NAME, where VALUE is
188 the text between the parens: NAME=( VALUE ) */
190 assign_array_from_string (name
, value
)
195 var
= find_or_make_array_variable (name
, 1);
197 return ((SHELL_VAR
*)NULL
);
199 return (assign_array_var_from_string (var
, value
));
202 /* Sequentially assign the indices of indexed array variable VAR from the
205 assign_array_var_from_word_list (var
, list
)
209 register arrayind_t i
;
210 register WORD_LIST
*l
;
213 for (a
= array_cell (var
), l
= list
, i
= 0; l
; l
= l
->next
, i
++)
214 if (var
->assign_func
)
215 (*var
->assign_func
) (var
, l
->word
->word
, i
);
217 array_insert (a
, i
, l
->word
->word
);
221 /* Perform a compound array assignment: VAR->name=( VALUE ). The
222 VALUE has already had the parentheses stripped. */
224 assign_array_var_from_string (var
, value
)
229 WORD_LIST
*list
, *nlist
;
230 char *w
, *val
, *nval
;
232 arrayind_t ind
, last_ind
;
237 /* If this is called from declare_builtin, value[0] == '(' and
238 xstrchr(value, ')') != 0. In this case, we need to extract
239 the value from between the parens before going on. */
240 if (*value
== '(') /*)*/
243 val
= extract_array_assignment_list (value
, &ni
);
250 /* Expand the value string into a list of words, performing all the
251 shell expansions including pathname generation and word splitting. */
252 /* First we split the string on whitespace, using the shell parser
253 (ksh93 seems to do this). */
254 list
= parse_string_to_word_list (val
, 1, "array assign");
256 /* If we're using [subscript]=value, we need to quote each [ and ] to
257 prevent unwanted filename expansion. */
259 quote_array_assignment_chars (list
);
261 /* Now that we've split it, perform the shell expansions on each
263 nlist
= list
? expand_words_no_vars (list
) : (WORD_LIST
*)NULL
;
265 dispose_words (list
);
270 a
= array_cell (var
);
272 /* Now that we are ready to assign values to the array, kill the existing
277 for (last_ind
= 0, list
= nlist
; list
; list
= list
->next
)
279 w
= list
->word
->word
;
281 /* We have a word of the form [ind]=value */
282 if ((list
->word
->flags
& W_ASSIGNMENT
) && w
[0] == '[')
284 len
= skipsubscript (w
, 0);
286 if (w
[len
] != ']' || w
[len
+1] != '=')
288 nval
= make_variable_value (var
, w
);
289 if (var
->assign_func
)
290 (*var
->assign_func
) (var
, nval
, last_ind
);
292 array_insert (a
, last_ind
, nval
);
304 if (ALL_ELEMENT_SUB (w
[1]) && len
== 2)
306 report_error (_("%s: cannot assign to non-numeric index"), w
);
310 ind
= array_expand_index (w
+ 1, len
);
319 else /* No [ind]=value, just a stray `=' */
326 this_command_name
= (char *)NULL
; /* no command name for errors */
327 nval
= make_variable_value (var
, val
);
328 if (var
->assign_func
)
329 (*var
->assign_func
) (var
, nval
, ind
);
331 array_insert (a
, ind
, nval
);
336 dispose_words (nlist
);
340 /* For each word in a compound array assignment, if the word looks like
341 [ind]=value, quote the `[' and `]' before the `=' to protect them from
342 unwanted filename expansion. */
344 quote_array_assignment_chars (list
)
351 for (l
= list
; l
; l
= l
->next
)
353 if (l
->word
== 0 || l
->word
->word
== 0 || l
->word
->word
[0] == '\0')
354 continue; /* should not happen, but just in case... */
355 /* Don't bother if it doesn't look like [ind]=value */
356 if (l
->word
->word
[0] != '[' || xstrchr (l
->word
->word
, '=') == 0) /* ] */
358 s
= nword
= (char *)xmalloc (strlen (l
->word
->word
) * 2 + 1);
360 for (t
= l
->word
->word
; *t
; )
364 if (saw_eq
== 0 && (*t
== '[' || *t
== ']'))
369 free (l
->word
->word
);
370 l
->word
->word
= nword
;
374 /* This function assumes s[i] == '['; returns with s[ret] == ']' if
375 an array subscript is correctly parsed. */
382 #if defined (HANDLE_MULTIBYTE)
383 mbstate_t state
, state_bak
;
384 size_t slength
, mblength
;
388 #if defined (HANDLE_MULTIBYTE)
389 memset (&state
, '\0', sizeof (mbstate_t));
390 slength
= strlen (s
+ i
);
391 mb_cur_max
= MB_CUR_MAX
;
397 /* Advance one (possibly multibyte) character in S starting at I. */
398 #if defined (HANDLE_MULTIBYTE)
402 mblength
= mbrlen (s
+ i
, slength
, &state
);
404 if (MB_INVALIDCH (mblength
))
410 else if (MB_NULLWCH (mblength
))
435 /* This function is called with SUB pointing to just after the beginning
436 `[' of an array subscript and removes the array element to which SUB
437 expands from array VAR. A subscript of `*' or `@' unsets the array. */
439 unbind_array_element (var
, sub
)
447 len
= skipsubscript (sub
, 0);
448 if (sub
[len
] != ']' || len
== 0)
450 builtin_error ("%s[%s: %s", var
->name
, sub
, _(bash_badsub_errmsg
));
455 if (ALL_ELEMENT_SUB (sub
[0]) && sub
[1] == 0)
457 unbind_variable (var
->name
);
460 ind
= array_expand_index (sub
, len
+1);
463 builtin_error ("[%s]: %s", sub
, _(bash_badsub_errmsg
));
466 ae
= array_remove (array_cell (var
), ind
);
468 array_dispose_element (ae
);
472 /* Format and output an array assignment in compound form VAR=(VALUES),
473 suitable for re-use as input. */
475 print_array_assignment (var
, quoted
)
481 vstr
= array_to_assign (array_cell (var
), quoted
);
484 printf ("%s=%s\n", var
->name
, quoted
? "'()'" : "()");
487 printf ("%s=%s\n", var
->name
, vstr
);
492 /***********************************************************************/
494 /* Utility functions to manage arrays and their contents for expansion */
496 /***********************************************************************/
498 /* Return 1 if NAME is a properly-formed array reference v[sub]. */
500 valid_array_reference (name
)
506 t
= xstrchr (name
, '['); /* ] */
510 r
= legal_identifier (name
);
514 /* Check for a properly-terminated non-blank subscript. */
515 len
= skipsubscript (t
, 0);
516 if (t
[len
] != ']' || len
== 1)
518 for (r
= 1; r
< len
; r
++)
519 if (whitespace (t
[r
]) == 0)
526 /* Expand the array index beginning at S and extending LEN characters. */
528 array_expand_index (s
, len
)
536 exp
= (char *)xmalloc (len
);
537 strncpy (exp
, s
, len
- 1);
539 t
= expand_string_to_string (exp
, 0);
540 this_command_name
= (char *)NULL
;
541 val
= evalexp (t
, &expok
);
546 last_command_exit_value
= EXECUTION_FAILURE
;
547 jump_to_top_level (DISCARD
);
552 /* Return the name of the variable specified by S without any subscript.
553 If SUBP is non-null, return a pointer to the start of the subscript
554 in *SUBP. If LENP is non-null, the length of the subscript is returned
555 in *LENP. This returns newly-allocated memory. */
557 array_variable_name (s
, subp
, lenp
)
564 t
= xstrchr (s
, '[');
571 return ((char *)NULL
);
574 ni
= skipsubscript (s
, ind
);
575 if (ni
<= ind
+ 1 || s
[ni
] != ']')
582 return ((char *)NULL
);
586 ret
= savestring (s
);
597 /* Return the variable specified by S without any subscript. If SUBP is
598 non-null, return a pointer to the start of the subscript in *SUBP.
599 If LENP is non-null, the length of the subscript is returned in *LENP. */
601 array_variable_part (s
, subp
, lenp
)
608 t
= array_variable_name (s
, subp
, lenp
);
610 return ((SHELL_VAR
*)NULL
);
611 var
= find_variable (t
);
614 return (var
== 0 || invisible_p (var
)) ? (SHELL_VAR
*)0 : var
;
617 /* Return a string containing the elements in the array and subscript
618 described by S. If the subscript is * or @, obeys quoting rules akin
619 to the expansion of $* and $@ including double quoting. If RTYPE
620 is non-null it gets 1 if the array reference is name[@] or name[*]
623 array_value_internal (s
, quoted
, allow_all
, rtype
)
625 int quoted
, allow_all
, *rtype
;
629 char *retval
, *t
, *temp
;
633 var
= array_variable_part (s
, &t
, &len
);
635 /* Expand the index, even if the variable doesn't exist, in case side
636 effects are needed, like ${w[i++]} where w is unset. */
643 return ((char *)NULL
); /* error message already printed */
646 if (ALL_ELEMENT_SUB (t
[0]) && t
[1] == ']')
653 return ((char *)NULL
);
656 return ((char *)NULL
);
657 else if (array_p (var
) == 0)
658 l
= add_string_to_list (value_cell (var
), (WORD_LIST
*)NULL
);
661 l
= array_to_word_list (array_cell (var
));
662 if (l
== (WORD_LIST
*)NULL
)
663 return ((char *) NULL
);
666 if (t
[0] == '*' && (quoted
& (Q_HERE_DOCUMENT
|Q_DOUBLE_QUOTES
)))
668 temp
= string_list_dollar_star (l
);
669 retval
= quote_string (temp
);
672 else /* ${name[@]} or unquoted ${name[*]} */
673 retval
= string_list_dollar_at (l
, quoted
);
681 ind
= array_expand_index (t
, len
);
685 err_badarraysub (var
->name
);
692 return ((char *)NULL
);
695 return ((char *)NULL
);
696 if (array_p (var
) == 0)
697 return (ind
== 0 ? value_cell (var
) : (char *)NULL
);
698 retval
= array_reference (array_cell (var
), ind
);
704 /* Return a string containing the elements described by the array and
705 subscript contained in S, obeying quoting for subscripts * and @. */
707 array_value (s
, quoted
, rtype
)
711 return (array_value_internal (s
, quoted
, 1, rtype
));
714 /* Return the value of the array indexing expression S as a single string.
715 If ALLOW_ALL is 0, do not allow `@' and `*' subscripts. This is used
716 by other parts of the shell such as the arithmetic expression evaluator
719 get_array_value (s
, allow_all
, rtype
)
721 int allow_all
, *rtype
;
723 return (array_value_internal (s
, 0, allow_all
, rtype
));
727 array_keys (s
, quoted
)
732 char *retval
, *t
, *temp
;
736 var
= array_variable_part (s
, &t
, &len
);
739 if (var
== 0 || ALL_ELEMENT_SUB (t
[0]) == 0 || t
[1] != ']')
742 if (array_p (var
) == 0)
743 l
= add_string_to_list ("0", (WORD_LIST
*)NULL
);
746 l
= array_keys_to_word_list (array_cell (var
));
747 if (l
== (WORD_LIST
*)NULL
)
748 return ((char *) NULL
);
751 if (t
[0] == '*' && (quoted
& (Q_HERE_DOCUMENT
|Q_DOUBLE_QUOTES
)))
753 temp
= string_list_dollar_star (l
);
754 retval
= quote_string (temp
);
757 else /* ${!name[@]} or unquoted ${!name[*]} */
758 retval
= string_list_dollar_at (l
, quoted
);
763 #endif /* ARRAY_VARS */