Fix bug #2238: the read.c:eval() function was not entirely reentrant.
[make/kirr.git] / function.c
blob2edac7460febec918d84916361ff6d3d18c0bae6
1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988, 1989, 1991-1997, 1999, 2002 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include "make.h"
21 #include "filedef.h"
22 #include "variable.h"
23 #include "dep.h"
24 #include "job.h"
25 #include "commands.h"
26 #include "debug.h"
28 #ifdef _AMIGA
29 #include "amiga.h"
30 #endif
33 struct function_table_entry
35 const char *name;
36 unsigned char len;
37 unsigned char minimum_args;
38 unsigned char maximum_args;
39 char expand_args;
40 char *(*func_ptr) PARAMS ((char *output, char **argv, const char *fname));
43 static unsigned long
44 function_table_entry_hash_1 (const void *keyv)
46 struct function_table_entry const *key = (struct function_table_entry const *) keyv;
47 return_STRING_N_HASH_1 (key->name, key->len);
50 static unsigned long
51 function_table_entry_hash_2 (const void *keyv)
53 struct function_table_entry const *key = (struct function_table_entry const *) keyv;
54 return_STRING_N_HASH_2 (key->name, key->len);
57 static int
58 function_table_entry_hash_cmp (const void *xv, const void *yv)
60 struct function_table_entry const *x = (struct function_table_entry const *) xv;
61 struct function_table_entry const *y = (struct function_table_entry const *) yv;
62 int result = x->len - y->len;
63 if (result)
64 return result;
65 return_STRING_N_COMPARE (x->name, y->name, x->len);
68 static struct hash_table function_table;
71 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
72 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
73 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
74 nonzero, substitutions are done only on matches which are complete
75 whitespace-delimited words. If SUFFIX_ONLY is nonzero, substitutions are
76 done only at the ends of whitespace-delimited words. */
78 char *
79 subst_expand (char *o, char *text, char *subst, char *replace,
80 unsigned int slen, unsigned int rlen,
81 int by_word, int suffix_only)
83 register char *t = text;
84 register char *p;
86 if (slen == 0 && !by_word && !suffix_only)
88 /* The first occurrence of "" in any string is its end. */
89 o = variable_buffer_output (o, t, strlen (t));
90 if (rlen > 0)
91 o = variable_buffer_output (o, replace, rlen);
92 return o;
97 if ((by_word | suffix_only) && slen == 0)
98 /* When matching by words, the empty string should match
99 the end of each word, rather than the end of the whole text. */
100 p = end_of_token (next_token (t));
101 else
103 p = sindex (t, 0, subst, slen);
104 if (p == 0)
106 /* No more matches. Output everything left on the end. */
107 o = variable_buffer_output (o, t, strlen (t));
108 return o;
112 /* Output everything before this occurrence of the string to replace. */
113 if (p > t)
114 o = variable_buffer_output (o, t, p - t);
116 /* If we're substituting only by fully matched words,
117 or only at the ends of words, check that this case qualifies. */
118 if ((by_word
119 && ((p > t && !isblank ((unsigned char)p[-1]))
120 || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
121 || (suffix_only
122 && (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
123 /* Struck out. Output the rest of the string that is
124 no longer to be replaced. */
125 o = variable_buffer_output (o, subst, slen);
126 else if (rlen > 0)
127 /* Output the replacement string. */
128 o = variable_buffer_output (o, replace, rlen);
130 /* Advance T past the string to be replaced. */
131 t = p + slen;
132 } while (*t != '\0');
134 return o;
138 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
139 and replacing strings matching PATTERN with REPLACE.
140 If PATTERN_PERCENT is not nil, PATTERN has already been
141 run through find_percent, and PATTERN_PERCENT is the result.
142 If REPLACE_PERCENT is not nil, REPLACE has already been
143 run through find_percent, and REPLACE_PERCENT is the result. */
145 char *
146 patsubst_expand (char *o, char *text, char *pattern, char *replace,
147 char *pattern_percent, char *replace_percent)
149 unsigned int pattern_prepercent_len, pattern_postpercent_len;
150 unsigned int replace_prepercent_len, replace_postpercent_len = 0;
151 char *t;
152 unsigned int len;
153 int doneany = 0;
155 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
156 will be collapsed before we call subst_expand if PATTERN has no %. */
157 if (replace_percent == 0)
158 replace_percent = find_percent (replace);
159 if (replace_percent != 0)
161 /* Record the length of REPLACE before and after the % so
162 we don't have to compute these lengths more than once. */
163 replace_prepercent_len = replace_percent - replace;
164 replace_postpercent_len = strlen (replace_percent + 1);
166 else
167 /* We store the length of the replacement
168 so we only need to compute it once. */
169 replace_prepercent_len = strlen (replace);
171 if (pattern_percent == 0)
172 pattern_percent = find_percent (pattern);
173 if (pattern_percent == 0)
174 /* With no % in the pattern, this is just a simple substitution. */
175 return subst_expand (o, text, pattern, replace,
176 strlen (pattern), strlen (replace), 1, 0);
178 /* Record the length of PATTERN before and after the %
179 so we don't have to compute it more than once. */
180 pattern_prepercent_len = pattern_percent - pattern;
181 pattern_postpercent_len = strlen (pattern_percent + 1);
183 while ((t = find_next_token (&text, &len)) != 0)
185 int fail = 0;
187 /* Is it big enough to match? */
188 if (len < pattern_prepercent_len + pattern_postpercent_len)
189 fail = 1;
191 /* Does the prefix match? */
192 if (!fail && pattern_prepercent_len > 0
193 && (*t != *pattern
194 || t[pattern_prepercent_len - 1] != pattern_percent[-1]
195 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
196 fail = 1;
198 /* Does the suffix match? */
199 if (!fail && pattern_postpercent_len > 0
200 && (t[len - 1] != pattern_percent[pattern_postpercent_len]
201 || t[len - pattern_postpercent_len] != pattern_percent[1]
202 || !strneq (&t[len - pattern_postpercent_len],
203 &pattern_percent[1], pattern_postpercent_len - 1)))
204 fail = 1;
206 if (fail)
207 /* It didn't match. Output the string. */
208 o = variable_buffer_output (o, t, len);
209 else
211 /* It matched. Output the replacement. */
213 /* Output the part of the replacement before the %. */
214 o = variable_buffer_output (o, replace, replace_prepercent_len);
216 if (replace_percent != 0)
218 /* Output the part of the matched string that
219 matched the % in the pattern. */
220 o = variable_buffer_output (o, t + pattern_prepercent_len,
221 len - (pattern_prepercent_len
222 + pattern_postpercent_len));
223 /* Output the part of the replacement after the %. */
224 o = variable_buffer_output (o, replace_percent + 1,
225 replace_postpercent_len);
229 /* Output a space, but not if the replacement is "". */
230 if (fail || replace_prepercent_len > 0
231 || (replace_percent != 0 && len + replace_postpercent_len > 0))
233 o = variable_buffer_output (o, " ", 1);
234 doneany = 1;
237 if (doneany)
238 /* Kill the last space. */
239 --o;
241 return o;
245 /* Look up a function by name. */
247 static const struct function_table_entry *
248 lookup_function (const char *s)
250 const char *e = s;
252 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
253 e++;
254 if (*e == '\0' || isblank ((unsigned char) *e))
256 struct function_table_entry function_table_entry_key;
257 function_table_entry_key.name = s;
258 function_table_entry_key.len = e - s;
260 return hash_find_item (&function_table, &function_table_entry_key);
262 return 0;
266 /* Return 1 if PATTERN matches STR, 0 if not. */
269 pattern_matches (char *pattern, char *percent, char *str)
271 unsigned int sfxlen, strlength;
273 if (percent == 0)
275 unsigned int len = strlen (pattern) + 1;
276 char *new_chars = (char *) alloca (len);
277 bcopy (pattern, new_chars, len);
278 pattern = new_chars;
279 percent = find_percent (pattern);
280 if (percent == 0)
281 return streq (pattern, str);
284 sfxlen = strlen (percent + 1);
285 strlength = strlen (str);
287 if (strlength < (percent - pattern) + sfxlen
288 || !strneq (pattern, str, percent - pattern))
289 return 0;
291 return !strcmp (percent + 1, str + (strlength - sfxlen));
295 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
296 ENDPARENtheses), starting at PTR before END. Return a pointer to
297 next character.
299 If no next argument is found, return NULL.
302 static char *
303 find_next_argument (char startparen, char endparen,
304 const char *ptr, const char *end)
306 int count = 0;
308 for (; ptr < end; ++ptr)
309 if (*ptr == startparen)
310 ++count;
312 else if (*ptr == endparen)
314 --count;
315 if (count < 0)
316 return NULL;
319 else if (*ptr == ',' && !count)
320 return (char *)ptr;
322 /* We didn't find anything. */
323 return NULL;
327 /* Glob-expand LINE. The returned pointer is
328 only good until the next call to string_glob. */
330 static char *
331 string_glob (char *line)
333 static char *result = 0;
334 static unsigned int length;
335 register struct nameseq *chain;
336 register unsigned int idx;
338 chain = multi_glob (parse_file_seq
339 (&line, '\0', sizeof (struct nameseq),
340 /* We do not want parse_file_seq to strip `./'s.
341 That would break examples like:
342 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
344 sizeof (struct nameseq));
346 if (result == 0)
348 length = 100;
349 result = (char *) xmalloc (100);
352 idx = 0;
353 while (chain != 0)
355 register char *name = chain->name;
356 unsigned int len = strlen (name);
358 struct nameseq *next = chain->next;
359 free ((char *) chain);
360 chain = next;
362 /* multi_glob will pass names without globbing metacharacters
363 through as is, but we want only files that actually exist. */
364 if (file_exists_p (name))
366 if (idx + len + 1 > length)
368 length += (len + 1) * 2;
369 result = (char *) xrealloc (result, length);
371 bcopy (name, &result[idx], len);
372 idx += len;
373 result[idx++] = ' ';
376 free (name);
379 /* Kill the last space and terminate the string. */
380 if (idx == 0)
381 result[0] = '\0';
382 else
383 result[idx - 1] = '\0';
385 return result;
389 Builtin functions
392 static char *
393 func_patsubst (char *o, char **argv, const char *funcname)
395 o = patsubst_expand (o, argv[2], argv[0], argv[1], (char *) 0, (char *) 0);
396 return o;
400 static char *
401 func_join (char *o, char **argv, const char *funcname)
403 int doneany = 0;
405 /* Write each word of the first argument directly followed
406 by the corresponding word of the second argument.
407 If the two arguments have a different number of words,
408 the excess words are just output separated by blanks. */
409 register char *tp;
410 register char *pp;
411 char *list1_iterator = argv[0];
412 char *list2_iterator = argv[1];
415 unsigned int len1, len2;
417 tp = find_next_token (&list1_iterator, &len1);
418 if (tp != 0)
419 o = variable_buffer_output (o, tp, len1);
421 pp = find_next_token (&list2_iterator, &len2);
422 if (pp != 0)
423 o = variable_buffer_output (o, pp, len2);
425 if (tp != 0 || pp != 0)
427 o = variable_buffer_output (o, " ", 1);
428 doneany = 1;
431 while (tp != 0 || pp != 0);
432 if (doneany)
433 /* Kill the last blank. */
434 --o;
436 return o;
440 static char *
441 func_origin (char *o, char **argv, const char *funcname)
443 /* Expand the argument. */
444 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
445 if (v == 0)
446 o = variable_buffer_output (o, "undefined", 9);
447 else
448 switch (v->origin)
450 default:
451 case o_invalid:
452 abort ();
453 break;
454 case o_default:
455 o = variable_buffer_output (o, "default", 7);
456 break;
457 case o_env:
458 o = variable_buffer_output (o, "environment", 11);
459 break;
460 case o_file:
461 o = variable_buffer_output (o, "file", 4);
462 break;
463 case o_env_override:
464 o = variable_buffer_output (o, "environment override", 20);
465 break;
466 case o_command:
467 o = variable_buffer_output (o, "command line", 12);
468 break;
469 case o_override:
470 o = variable_buffer_output (o, "override", 8);
471 break;
472 case o_automatic:
473 o = variable_buffer_output (o, "automatic", 9);
474 break;
477 return o;
480 #ifdef VMS
481 # define IS_PATHSEP(c) ((c) == ']')
482 #else
483 # ifdef HAVE_DOS_PATHS
484 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
485 # else
486 # define IS_PATHSEP(c) ((c) == '/')
487 # endif
488 #endif
491 static char *
492 func_notdir_suffix (char *o, char **argv, const char *funcname)
494 /* Expand the argument. */
495 char *list_iterator = argv[0];
496 char *p2 =0;
497 int doneany =0;
498 unsigned int len=0;
500 int is_suffix = streq (funcname, "suffix");
501 int is_notdir = !is_suffix;
502 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
504 char *p = p2 + len;
507 while (p >= p2 && (!is_suffix || *p != '.'))
509 if (IS_PATHSEP (*p))
510 break;
511 --p;
514 if (p >= p2)
516 if (is_notdir)
517 ++p;
518 else if (*p != '.')
519 continue;
520 o = variable_buffer_output (o, p, len - (p - p2));
522 #ifdef HAVE_DOS_PATHS
523 /* Handle the case of "d:foo/bar". */
524 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
526 p = p2 + 2;
527 o = variable_buffer_output (o, p, len - (p - p2));
529 #endif
530 else if (is_notdir)
531 o = variable_buffer_output (o, p2, len);
533 if (is_notdir || p >= p2)
535 o = variable_buffer_output (o, " ", 1);
536 doneany = 1;
539 if (doneany)
540 /* Kill last space. */
541 --o;
544 return o;
549 static char *
550 func_basename_dir (char *o, char **argv, const char *funcname)
552 /* Expand the argument. */
553 char *p3 = argv[0];
554 char *p2=0;
555 int doneany=0;
556 unsigned int len=0;
557 char *p=0;
558 int is_basename= streq (funcname, "basename");
559 int is_dir= !is_basename;
561 while ((p2 = find_next_token (&p3, &len)) != 0)
563 p = p2 + len;
564 while (p >= p2 && (!is_basename || *p != '.'))
566 if (IS_PATHSEP (*p))
567 break;
568 --p;
571 if (p >= p2 && (is_dir))
572 o = variable_buffer_output (o, p2, ++p - p2);
573 else if (p >= p2 && (*p == '.'))
574 o = variable_buffer_output (o, p2, p - p2);
575 #ifdef HAVE_DOS_PATHS
576 /* Handle the "d:foobar" case */
577 else if (p2[0] && p2[1] == ':' && is_dir)
578 o = variable_buffer_output (o, p2, 2);
579 #endif
580 else if (is_dir)
581 #ifdef VMS
582 o = variable_buffer_output (o, "[]", 2);
583 #else
584 #ifndef _AMIGA
585 o = variable_buffer_output (o, "./", 2);
586 #else
587 ; /* Just a nop... */
588 #endif /* AMIGA */
589 #endif /* !VMS */
590 else
591 /* The entire name is the basename. */
592 o = variable_buffer_output (o, p2, len);
594 o = variable_buffer_output (o, " ", 1);
595 doneany = 1;
597 if (doneany)
598 /* Kill last space. */
599 --o;
602 return o;
605 static char *
606 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
608 int fixlen = strlen (argv[0]);
609 char *list_iterator = argv[1];
610 int is_addprefix = streq (funcname, "addprefix");
611 int is_addsuffix = !is_addprefix;
613 int doneany = 0;
614 char *p;
615 unsigned int len;
617 while ((p = find_next_token (&list_iterator, &len)) != 0)
619 if (is_addprefix)
620 o = variable_buffer_output (o, argv[0], fixlen);
621 o = variable_buffer_output (o, p, len);
622 if (is_addsuffix)
623 o = variable_buffer_output (o, argv[0], fixlen);
624 o = variable_buffer_output (o, " ", 1);
625 doneany = 1;
628 if (doneany)
629 /* Kill last space. */
630 --o;
632 return o;
635 static char *
636 func_subst (char *o, char **argv, const char *funcname)
638 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
639 strlen (argv[1]), 0, 0);
641 return o;
645 static char *
646 func_firstword (char *o, char **argv, const char *funcname)
648 unsigned int i;
649 char *words = argv[0]; /* Use a temp variable for find_next_token */
650 char *p = find_next_token (&words, &i);
652 if (p != 0)
653 o = variable_buffer_output (o, p, i);
655 return o;
659 static char *
660 func_words (char *o, char **argv, const char *funcname)
662 int i = 0;
663 char *word_iterator = argv[0];
664 char buf[20];
666 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
667 ++i;
669 sprintf (buf, "%d", i);
670 o = variable_buffer_output (o, buf, strlen (buf));
673 return o;
676 static char *
677 strip_whitespace (const char **begpp, const char **endpp)
679 while (isspace ((unsigned char)**begpp) && *begpp <= *endpp)
680 (*begpp) ++;
681 while (isspace ((unsigned char)**endpp) && *endpp >= *begpp)
682 (*endpp) --;
683 return (char *)*begpp;
686 static void
687 check_numeric (const char *s, const char *message)
689 const char *end = s + strlen (s) - 1;
690 const char *beg = s;
691 strip_whitespace (&s, &end);
693 for (; s <= end; ++s)
694 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
695 break;
697 if (s <= end || end - beg < 0)
698 fatal (reading_file, "%s: '%s'", message, beg);
703 static char *
704 func_word (char *o, char **argv, const char *funcname)
706 char *end_p=0;
707 int i=0;
708 char *p=0;
710 /* Check the first argument. */
711 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
712 i = atoi (argv[0]);
714 if (i == 0)
715 fatal (reading_file, _("first argument to `word' function must be greater than 0"));
718 end_p = argv[1];
719 while ((p = find_next_token (&end_p, 0)) != 0)
720 if (--i == 0)
721 break;
723 if (i == 0)
724 o = variable_buffer_output (o, p, end_p - p);
726 return o;
729 static char *
730 func_wordlist (char *o, char **argv, const char *funcname)
732 int start, count;
734 /* Check the arguments. */
735 check_numeric (argv[0],
736 _("non-numeric first argument to `wordlist' function"));
737 check_numeric (argv[1],
738 _("non-numeric second argument to `wordlist' function"));
740 start = atoi (argv[0]);
741 count = atoi (argv[1]) - start + 1;
743 if (count > 0)
745 char *p;
746 char *end_p = argv[2];
748 /* Find the beginning of the "start"th word. */
749 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
752 if (p)
754 /* Find the end of the "count"th word from start. */
755 while (--count && (find_next_token (&end_p, 0) != 0))
758 /* Return the stuff in the middle. */
759 o = variable_buffer_output (o, p, end_p - p);
763 return o;
766 static char*
767 func_findstring (char *o, char **argv, const char *funcname)
769 /* Find the first occurrence of the first string in the second. */
770 int i = strlen (argv[0]);
771 if (sindex (argv[1], 0, argv[0], i) != 0)
772 o = variable_buffer_output (o, argv[0], i);
774 return o;
777 static char *
778 func_foreach (char *o, char **argv, const char *funcname)
780 /* expand only the first two. */
781 char *varname = expand_argument (argv[0], NULL);
782 char *list = expand_argument (argv[1], NULL);
783 char *body = argv[2];
785 int doneany = 0;
786 char *list_iterator = list;
787 char *p;
788 unsigned int len;
789 register struct variable *var;
791 push_new_variable_scope ();
792 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
794 /* loop through LIST, put the value in VAR and expand BODY */
795 while ((p = find_next_token (&list_iterator, &len)) != 0)
797 char *result = 0;
800 char save = p[len];
802 p[len] = '\0';
803 free (var->value);
804 var->value = (char *) xstrdup ((char*) p);
805 p[len] = save;
808 result = allocated_variable_expand (body);
810 o = variable_buffer_output (o, result, strlen (result));
811 o = variable_buffer_output (o, " ", 1);
812 doneany = 1;
813 free (result);
816 if (doneany)
817 /* Kill the last space. */
818 --o;
820 pop_variable_scope ();
821 free (varname);
822 free (list);
824 return o;
827 struct a_word
829 struct a_word *next;
830 struct a_word *chain;
831 char *str;
832 int length;
833 int matched;
836 static unsigned long
837 a_word_hash_1 (const void *key)
839 return_STRING_HASH_1 (((struct a_word const *) key)->str);
842 static unsigned long
843 a_word_hash_2 (const void *key)
845 return_STRING_HASH_2 (((struct a_word const *) key)->str);
848 static int
849 a_word_hash_cmp (const void *x, const void *y)
851 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
852 if (result)
853 return result;
854 return_STRING_COMPARE (((struct a_word const *) x)->str,
855 ((struct a_word const *) y)->str);
858 struct a_pattern
860 struct a_pattern *next;
861 char *str;
862 char *percent;
863 int length;
864 int save_c;
867 static char *
868 func_filter_filterout (char *o, char **argv, const char *funcname)
870 struct a_word *wordhead;
871 struct a_word **wordtail;
872 struct a_word *wp;
873 struct a_pattern *pathead;
874 struct a_pattern **pattail;
875 struct a_pattern *pp;
877 struct hash_table a_word_table;
878 int is_filter = streq (funcname, "filter");
879 char *pat_iterator = argv[0];
880 char *word_iterator = argv[1];
881 int literals = 0;
882 int words = 0;
883 int hashing = 0;
884 char *p;
885 unsigned int len;
887 /* Chop ARGV[0] up into patterns to match against the words. */
889 pattail = &pathead;
890 while ((p = find_next_token (&pat_iterator, &len)) != 0)
892 struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
894 *pattail = pat;
895 pattail = &pat->next;
897 if (*pat_iterator != '\0')
898 ++pat_iterator;
900 pat->str = p;
901 pat->length = len;
902 pat->save_c = p[len];
903 p[len] = '\0';
904 pat->percent = find_percent (p);
905 if (pat->percent == 0)
906 literals++;
908 *pattail = 0;
910 /* Chop ARGV[1] up into words to match against the patterns. */
912 wordtail = &wordhead;
913 while ((p = find_next_token (&word_iterator, &len)) != 0)
915 struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
917 *wordtail = word;
918 wordtail = &word->next;
920 if (*word_iterator != '\0')
921 ++word_iterator;
923 p[len] = '\0';
924 word->str = p;
925 word->length = len;
926 word->matched = 0;
927 word->chain = 0;
928 words++;
930 *wordtail = 0;
932 /* Only use a hash table if arg list lengths justifies the cost. */
933 hashing = (literals >= 2 && (literals * words) >= 10);
934 if (hashing)
936 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
937 for (wp = wordhead; wp != 0; wp = wp->next)
939 struct a_word *owp = hash_insert (&a_word_table, wp);
940 if (owp)
941 wp->chain = owp;
945 if (words)
947 int doneany = 0;
949 /* Run each pattern through the words, killing words. */
950 for (pp = pathead; pp != 0; pp = pp->next)
952 if (pp->percent)
953 for (wp = wordhead; wp != 0; wp = wp->next)
954 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
955 else if (hashing)
957 struct a_word a_word_key;
958 a_word_key.str = pp->str;
959 a_word_key.length = pp->length;
960 wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
961 while (wp)
963 wp->matched |= 1;
964 wp = wp->chain;
967 else
968 for (wp = wordhead; wp != 0; wp = wp->next)
969 wp->matched |= (wp->length == pp->length
970 && strneq (pp->str, wp->str, wp->length));
973 /* Output the words that matched (or didn't, for filter-out). */
974 for (wp = wordhead; wp != 0; wp = wp->next)
975 if (is_filter ? wp->matched : !wp->matched)
977 o = variable_buffer_output (o, wp->str, strlen (wp->str));
978 o = variable_buffer_output (o, " ", 1);
979 doneany = 1;
982 if (doneany)
983 /* Kill the last space. */
984 --o;
987 for (pp = pathead; pp != 0; pp = pp->next)
988 pp->str[pp->length] = pp->save_c;
990 if (hashing)
991 hash_free (&a_word_table, 0);
993 return o;
997 static char *
998 func_strip (char *o, char **argv, const char *funcname)
1000 char *p = argv[0];
1001 int doneany =0;
1003 while (*p != '\0')
1005 int i=0;
1006 char *word_start=0;
1008 while (isspace ((unsigned char)*p))
1009 ++p;
1010 word_start = p;
1011 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1013 if (!i)
1014 break;
1015 o = variable_buffer_output (o, word_start, i);
1016 o = variable_buffer_output (o, " ", 1);
1017 doneany = 1;
1020 if (doneany)
1021 /* Kill the last space. */
1022 --o;
1023 return o;
1027 Print a warning or fatal message.
1029 static char *
1030 func_error (char *o, char **argv, const char *funcname)
1032 char **argvp;
1033 char *msg, *p;
1034 int len;
1036 /* The arguments will be broken on commas. Rather than create yet
1037 another special case where function arguments aren't broken up,
1038 just create a format string that puts them back together. */
1039 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1040 len += strlen (*argvp) + 2;
1042 p = msg = (char *) alloca (len + 1);
1044 for (argvp=argv; argvp[1] != 0; ++argvp)
1046 strcpy (p, *argvp);
1047 p += strlen (*argvp);
1048 *(p++) = ',';
1049 *(p++) = ' ';
1051 strcpy (p, *argvp);
1053 if (*funcname == 'e')
1054 fatal (reading_file, "%s", msg);
1056 /* The warning function expands to the empty string. */
1057 error (reading_file, "%s", msg);
1059 return o;
1064 chop argv[0] into words, and sort them.
1066 static char *
1067 func_sort (char *o, char **argv, const char *funcname)
1069 char **words = 0;
1070 int nwords = 0;
1071 register int wordi = 0;
1073 /* Chop ARGV[0] into words and put them in WORDS. */
1074 char *t = argv[0];
1075 char *p;
1076 unsigned int len;
1077 int i;
1079 while ((p = find_next_token (&t, &len)) != 0)
1081 if (wordi >= nwords - 1)
1083 nwords = (2 * nwords) + 5;
1084 words = (char **) xrealloc ((char *) words,
1085 nwords * sizeof (char *));
1087 words[wordi++] = savestring (p, len);
1090 if (!wordi)
1091 return o;
1093 /* Now sort the list of words. */
1094 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1096 /* Now write the sorted list. */
1097 for (i = 0; i < wordi; ++i)
1099 len = strlen (words[i]);
1100 if (i == wordi - 1 || strlen (words[i + 1]) != len
1101 || strcmp (words[i], words[i + 1]))
1103 o = variable_buffer_output (o, words[i], len);
1104 o = variable_buffer_output (o, " ", 1);
1106 free (words[i]);
1108 /* Kill the last space. */
1109 --o;
1111 free (words);
1113 return o;
1117 $(if condition,true-part[,false-part])
1119 CONDITION is false iff it evaluates to an empty string. White
1120 space before and after condition are stripped before evaluation.
1122 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1123 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1124 you can use $(if ...) to create side-effects (with $(shell ...), for
1125 example).
1128 static char *
1129 func_if (char *o, char **argv, const char *funcname)
1131 const char *begp = argv[0];
1132 const char *endp = begp + strlen (argv[0]);
1133 int result = 0;
1135 /* Find the result of the condition: if we have a value, and it's not
1136 empty, the condition is true. If we don't have a value, or it's the
1137 empty string, then it's false. */
1139 strip_whitespace (&begp, &endp);
1141 if (begp < endp)
1143 char *expansion = expand_argument (begp, NULL);
1145 result = strlen (expansion);
1146 free (expansion);
1149 /* If the result is true (1) we want to eval the first argument, and if
1150 it's false (0) we want to eval the second. If the argument doesn't
1151 exist we do nothing, otherwise expand it and add to the buffer. */
1153 argv += 1 + !result;
1155 if (argv[0])
1157 char *expansion;
1159 expansion = expand_argument (argv[0], NULL);
1161 o = variable_buffer_output (o, expansion, strlen (expansion));
1163 free (expansion);
1166 return o;
1169 static char *
1170 func_wildcard (char *o, char **argv, const char *funcname)
1173 #ifdef _AMIGA
1174 o = wildcard_expansion (argv[0], o);
1175 #else
1176 char *p = string_glob (argv[0]);
1177 o = variable_buffer_output (o, p, strlen (p));
1178 #endif
1179 return o;
1183 $(eval <makefile string>)
1185 Always resolves to the empty string.
1187 Treat the arguments as a segment of makefile, and parse them.
1190 static char *
1191 func_eval (char *o, char **argv, const char *funcname)
1193 char *buf;
1194 unsigned int len;
1196 /* Eval the buffer. Pop the current variable buffer setting so that the
1197 eval'd code can use its own without conflicting. */
1199 install_variable_buffer (&buf, &len);
1201 eval_buffer (argv[0]);
1203 restore_variable_buffer (buf, len);
1205 return o;
1209 static char *
1210 func_value (char *o, char **argv, const char *funcname)
1212 /* Look up the variable. */
1213 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1215 /* Copy its value into the output buffer without expanding it. */
1216 if (v)
1217 o = variable_buffer_output (o, v->value, strlen(v->value));
1219 return o;
1223 \r is replaced on UNIX as well. Is this desirable?
1225 void
1226 fold_newlines (char *buffer, int *length)
1228 char *dst = buffer;
1229 char *src = buffer;
1230 char *last_nonnl = buffer -1;
1231 src[*length] = 0;
1232 for (; *src != '\0'; ++src)
1234 if (src[0] == '\r' && src[1] == '\n')
1235 continue;
1236 if (*src == '\n')
1238 *dst++ = ' ';
1240 else
1242 last_nonnl = dst;
1243 *dst++ = *src;
1246 *(++last_nonnl) = '\0';
1247 *length = last_nonnl - buffer;
1252 int shell_function_pid = 0, shell_function_completed;
1255 #ifdef WINDOWS32
1256 /*untested*/
1258 #include <windows.h>
1259 #include <io.h>
1260 #include "sub_proc.h"
1263 void
1264 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1266 SECURITY_ATTRIBUTES saAttr;
1267 HANDLE hIn;
1268 HANDLE hErr;
1269 HANDLE hChildOutRd;
1270 HANDLE hChildOutWr;
1271 HANDLE hProcess;
1274 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1275 saAttr.bInheritHandle = TRUE;
1276 saAttr.lpSecurityDescriptor = NULL;
1278 if (DuplicateHandle (GetCurrentProcess(),
1279 GetStdHandle(STD_INPUT_HANDLE),
1280 GetCurrentProcess(),
1281 &hIn,
1283 TRUE,
1284 DUPLICATE_SAME_ACCESS) == FALSE) {
1285 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1286 GetLastError());
1289 if (DuplicateHandle(GetCurrentProcess(),
1290 GetStdHandle(STD_ERROR_HANDLE),
1291 GetCurrentProcess(),
1292 &hErr,
1294 TRUE,
1295 DUPLICATE_SAME_ACCESS) == FALSE) {
1296 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1297 GetLastError());
1300 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1301 fatal (NILF, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1303 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1305 if (!hProcess)
1306 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1308 /* make sure that CreateProcess() has Path it needs */
1309 sync_Path_environment();
1311 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1312 /* register process for wait */
1313 process_register(hProcess);
1315 /* set the pid for returning to caller */
1316 *pid_p = (int) hProcess;
1318 /* set up to read data from child */
1319 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1321 /* this will be closed almost right away */
1322 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1323 } else {
1324 /* reap/cleanup the failed process */
1325 process_cleanup(hProcess);
1327 /* close handles which were duplicated, they weren't used */
1328 CloseHandle(hIn);
1329 CloseHandle(hErr);
1331 /* close pipe handles, they won't be used */
1332 CloseHandle(hChildOutRd);
1333 CloseHandle(hChildOutWr);
1335 /* set status for return */
1336 pipedes[0] = pipedes[1] = -1;
1337 *pid_p = -1;
1340 #endif
1343 #ifdef __MSDOS__
1344 FILE *
1345 msdos_openpipe (int* pipedes, int *pidp, char *text)
1347 FILE *fpipe=0;
1348 /* MSDOS can't fork, but it has `popen'. */
1349 struct variable *sh = lookup_variable ("SHELL", 5);
1350 int e;
1351 extern int dos_command_running, dos_status;
1353 /* Make sure not to bother processing an empty line. */
1354 while (isblank ((unsigned char)*text))
1355 ++text;
1356 if (*text == '\0')
1357 return 0;
1359 if (sh)
1361 char buf[PATH_MAX + 7];
1362 /* This makes sure $SHELL value is used by $(shell), even
1363 though the target environment is not passed to it. */
1364 sprintf (buf, "SHELL=%s", sh->value);
1365 putenv (buf);
1368 e = errno;
1369 errno = 0;
1370 dos_command_running = 1;
1371 dos_status = 0;
1372 /* If dos_status becomes non-zero, it means the child process
1373 was interrupted by a signal, like SIGINT or SIGQUIT. See
1374 fatal_error_signal in commands.c. */
1375 fpipe = popen (text, "rt");
1376 dos_command_running = 0;
1377 if (!fpipe || dos_status)
1379 pipedes[0] = -1;
1380 *pidp = -1;
1381 if (dos_status)
1382 errno = EINTR;
1383 else if (errno == 0)
1384 errno = ENOMEM;
1385 shell_function_completed = -1;
1387 else
1389 pipedes[0] = fileno (fpipe);
1390 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1391 errno = e;
1392 shell_function_completed = 1;
1394 return fpipe;
1396 #endif
1399 Do shell spawning, with the naughty bits for different OSes.
1402 #ifdef VMS
1404 /* VMS can't do $(shell ...) */
1405 #define func_shell 0
1407 #else
1408 #ifndef _AMIGA
1409 static char *
1410 func_shell (char *o, char **argv, const char *funcname)
1412 char* batch_filename = NULL;
1413 int i;
1415 #ifdef __MSDOS__
1416 FILE *fpipe;
1417 #endif
1418 char **command_argv;
1419 char *error_prefix;
1420 char **envp;
1421 int pipedes[2];
1422 int pid;
1424 #ifndef __MSDOS__
1425 /* Construct the argument list. */
1426 command_argv = construct_command_argv (argv[0],
1427 (char **) NULL, (struct file *) 0,
1428 &batch_filename);
1429 if (command_argv == 0)
1430 return o;
1431 #endif
1433 /* Using a target environment for `shell' loses in cases like:
1434 export var = $(shell echo foobie)
1435 because target_environment hits a loop trying to expand $(var)
1436 to put it in the environment. This is even more confusing when
1437 var was not explicitly exported, but just appeared in the
1438 calling environment. */
1440 envp = environ;
1442 /* For error messages. */
1443 if (reading_file != 0)
1445 error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1446 sprintf (error_prefix,
1447 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1449 else
1450 error_prefix = "";
1452 #ifdef WINDOWS32
1453 windows32_openpipe (pipedes, &pid, command_argv, envp);
1455 if (pipedes[0] < 0) {
1456 /* open of the pipe failed, mark as failed execution */
1457 shell_function_completed = -1;
1459 return o;
1460 } else
1461 #else /* WINDOWS32 */
1463 # ifdef __MSDOS__
1464 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1465 if (pipedes[0] < 0)
1467 perror_with_name (error_prefix, "pipe");
1468 return o;
1470 # else
1471 if (pipe (pipedes) < 0)
1473 perror_with_name (error_prefix, "pipe");
1474 return o;
1477 pid = vfork ();
1478 if (pid < 0)
1479 perror_with_name (error_prefix, "fork");
1480 else if (pid == 0)
1481 child_execute_job (0, pipedes[1], command_argv, envp);
1482 else
1483 # endif /* ! __MSDOS__ */
1485 #endif /* WINDOWS32 */
1487 /* We are the parent. */
1489 char *buffer;
1490 unsigned int maxlen;
1491 int cc;
1493 /* Record the PID for reap_children. */
1494 shell_function_pid = pid;
1495 #ifndef __MSDOS__
1496 shell_function_completed = 0;
1498 /* Free the storage only the child needed. */
1499 free (command_argv[0]);
1500 free ((char *) command_argv);
1502 /* Close the write side of the pipe. */
1503 (void) close (pipedes[1]);
1504 #endif
1506 /* Set up and read from the pipe. */
1508 maxlen = 200;
1509 buffer = (char *) xmalloc (maxlen + 1);
1511 /* Read from the pipe until it gets EOF. */
1512 for (i = 0; ; i += cc)
1514 if (i == maxlen)
1516 maxlen += 512;
1517 buffer = (char *) xrealloc (buffer, maxlen + 1);
1520 cc = read (pipedes[0], &buffer[i], maxlen - i);
1521 if (cc <= 0)
1522 break;
1524 buffer[i] = '\0';
1526 /* Close the read side of the pipe. */
1527 #ifdef __MSDOS__
1528 if (fpipe)
1529 (void) pclose (fpipe);
1530 #else
1531 (void) close (pipedes[0]);
1532 #endif
1534 /* Loop until child_handler sets shell_function_completed
1535 to the status of our child shell. */
1536 while (shell_function_completed == 0)
1537 reap_children (1, 0);
1539 if (batch_filename) {
1540 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1541 batch_filename));
1542 remove (batch_filename);
1543 free (batch_filename);
1545 shell_function_pid = 0;
1547 /* The child_handler function will set shell_function_completed
1548 to 1 when the child dies normally, or to -1 if it
1549 dies with status 127, which is most likely an exec fail. */
1551 if (shell_function_completed == -1)
1553 /* This most likely means that the execvp failed,
1554 so we should just write out the error message
1555 that came in over the pipe from the child. */
1556 fputs (buffer, stderr);
1557 fflush (stderr);
1559 else
1561 /* The child finished normally. Replace all
1562 newlines in its output with spaces, and put
1563 that in the variable output buffer. */
1564 fold_newlines (buffer, &i);
1565 o = variable_buffer_output (o, buffer, i);
1568 free (buffer);
1571 return o;
1574 #else /* _AMIGA */
1576 /* Do the Amiga version of func_shell. */
1578 static char *
1579 func_shell (char *o, char **argv, const char *funcname)
1581 /* Amiga can't fork nor spawn, but I can start a program with
1582 redirection of my choice. However, this means that we
1583 don't have an opportunity to reopen stdout to trap it. Thus,
1584 we save our own stdout onto a new descriptor and dup a temp
1585 file's descriptor onto our stdout temporarily. After we
1586 spawn the shell program, we dup our own stdout back to the
1587 stdout descriptor. The buffer reading is the same as above,
1588 except that we're now reading from a file. */
1590 #include <dos/dos.h>
1591 #include <proto/dos.h>
1593 BPTR child_stdout;
1594 char tmp_output[FILENAME_MAX];
1595 unsigned int maxlen = 200;
1596 int cc, i;
1597 char * buffer, * ptr;
1598 char ** aptr;
1599 int len = 0;
1600 char* batch_filename = NULL;
1602 /* Construct the argument list. */
1603 command_argv = construct_command_argv (argv[0], (char **) NULL,
1604 (struct file *) 0, &batch_filename);
1605 if (command_argv == 0)
1606 return o;
1608 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1609 Ideally we would use main.c:open_tmpfile(), but this uses a special
1610 Open(), not fopen(), and I'm not familiar enough with the code to mess
1611 with it. */
1612 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1613 mktemp (tmp_output);
1614 child_stdout = Open (tmp_output, MODE_NEWFILE);
1616 for (aptr=command_argv; *aptr; aptr++)
1617 len += strlen (*aptr) + 1;
1619 buffer = xmalloc (len + 1);
1620 ptr = buffer;
1622 for (aptr=command_argv; *aptr; aptr++)
1624 strcpy (ptr, *aptr);
1625 ptr += strlen (ptr) + 1;
1626 *ptr ++ = ' ';
1627 *ptr = 0;
1630 ptr[-1] = '\n';
1632 Execute (buffer, NULL, child_stdout);
1633 free (buffer);
1635 Close (child_stdout);
1637 child_stdout = Open (tmp_output, MODE_OLDFILE);
1639 buffer = xmalloc (maxlen);
1640 i = 0;
1643 if (i == maxlen)
1645 maxlen += 512;
1646 buffer = (char *) xrealloc (buffer, maxlen + 1);
1649 cc = Read (child_stdout, &buffer[i], maxlen - i);
1650 if (cc > 0)
1651 i += cc;
1652 } while (cc > 0);
1654 Close (child_stdout);
1656 fold_newlines (buffer, &i);
1657 o = variable_buffer_output (o, buffer, i);
1658 free (buffer);
1659 return o;
1661 #endif /* _AMIGA */
1662 #endif /* !VMS */
1664 #ifdef EXPERIMENTAL
1667 equality. Return is string-boolean, ie, the empty string is false.
1669 static char *
1670 func_eq (char* o, char **argv, char *funcname)
1672 int result = ! strcmp (argv[0], argv[1]);
1673 o = variable_buffer_output (o, result ? "1" : "", result);
1674 return o;
1679 string-boolean not operator.
1681 static char *
1682 func_not (char* o, char **argv, char *funcname)
1684 char * s = argv[0];
1685 int result = 0;
1686 while (isspace ((unsigned char)*s))
1687 s++;
1688 result = ! (*s);
1689 o = variable_buffer_output (o, result ? "1" : "", result);
1690 return o;
1692 #endif
1695 /* Lookup table for builtin functions.
1697 This doesn't have to be sorted; we use a straight lookup. We might gain
1698 some efficiency by moving most often used functions to the start of the
1699 table.
1701 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1702 comma-separated values are treated as arguments.
1704 EXPAND_ARGS means that all arguments should be expanded before invocation.
1705 Functions that do namespace tricks (foreach) don't automatically expand. */
1707 static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
1710 static struct function_table_entry function_table_init[] =
1712 /* Name/size */ /* MIN MAX EXP? Function */
1713 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
1714 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
1715 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
1716 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
1717 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
1718 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
1719 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
1720 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
1721 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
1722 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
1723 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
1724 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
1725 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
1726 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
1727 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
1728 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
1729 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
1730 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
1731 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
1732 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
1733 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
1734 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
1735 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
1736 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
1737 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
1738 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
1739 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
1740 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
1741 #ifdef EXPERIMENTAL
1742 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
1743 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
1744 #endif
1747 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1750 /* These must come after the definition of function_table. */
1752 static char *
1753 expand_builtin_function (char *o, int argc, char **argv,
1754 const struct function_table_entry *entry_p)
1756 if (argc < (int)entry_p->minimum_args)
1757 fatal (reading_file,
1758 _("Insufficient number of arguments (%d) to function `%s'"),
1759 argc, entry_p->name);
1761 /* I suppose technically some function could do something with no
1762 arguments, but so far none do, so just test it for all functions here
1763 rather than in each one. We can change it later if necessary. */
1765 if (!argc)
1766 return o;
1768 if (!entry_p->func_ptr)
1769 fatal (reading_file, _("Unimplemented on this platform: function `%s'"),
1770 entry_p->name);
1772 return entry_p->func_ptr (o, argv, entry_p->name);
1775 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1776 opening ( or { and is not null-terminated. If a function invocation
1777 is found, expand it into the buffer at *OP, updating *OP, incrementing
1778 *STRINGP past the reference and returning nonzero. If not, return zero. */
1781 handle_function (char **op, char **stringp)
1783 const struct function_table_entry *entry_p;
1784 char openparen = (*stringp)[0];
1785 char closeparen = openparen == '(' ? ')' : '}';
1786 char *beg;
1787 char *end;
1788 int count = 0;
1789 register char *p;
1790 char **argv, **argvp;
1791 int nargs;
1793 beg = *stringp + 1;
1795 entry_p = lookup_function (beg);
1797 if (!entry_p)
1798 return 0;
1800 /* We found a builtin function. Find the beginning of its arguments (skip
1801 whitespace after the name). */
1803 beg = next_token (beg + entry_p->len);
1805 /* Find the end of the function invocation, counting nested use of
1806 whichever kind of parens we use. Since we're looking, count commas
1807 to get a rough estimate of how many arguments we might have. The
1808 count might be high, but it'll never be low. */
1810 for (nargs=1, end=beg; *end != '\0'; ++end)
1811 if (*end == ',')
1812 ++nargs;
1813 else if (*end == openparen)
1814 ++count;
1815 else if (*end == closeparen && --count < 0)
1816 break;
1818 if (count >= 0)
1819 fatal (reading_file,
1820 _("unterminated call to function `%s': missing `%c'"),
1821 entry_p->name, closeparen);
1823 *stringp = end;
1825 /* Get some memory to store the arg pointers. */
1826 argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
1828 /* Chop the string into arguments, then a nul. As soon as we hit
1829 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1830 last argument.
1832 If we're expanding, store pointers to the expansion of each one. If
1833 not, make a duplicate of the string and point into that, nul-terminating
1834 each argument. */
1836 if (!entry_p->expand_args)
1838 int len = end - beg;
1840 p = xmalloc (len+1);
1841 memcpy (p, beg, len);
1842 p[len] = '\0';
1843 beg = p;
1844 end = beg + len;
1847 for (p=beg, nargs=0; p <= end; ++argvp)
1849 char *next;
1851 ++nargs;
1853 if (nargs == entry_p->maximum_args
1854 || (! (next = find_next_argument (openparen, closeparen, p, end))))
1855 next = end;
1857 if (entry_p->expand_args)
1858 *argvp = expand_argument (p, next);
1859 else
1861 *argvp = p;
1862 *next = '\0';
1865 p = next + 1;
1867 *argvp = NULL;
1869 /* Finally! Run the function... */
1870 *op = expand_builtin_function (*op, nargs, argv, entry_p);
1872 /* Free memory. */
1873 if (entry_p->expand_args)
1874 for (argvp=argv; *argvp != 0; ++argvp)
1875 free (*argvp);
1876 else
1877 free (beg);
1879 return 1;
1883 /* User-defined functions. Expand the first argument as either a builtin
1884 function or a make variable, in the context of the rest of the arguments
1885 assigned to $1, $2, ... $N. $0 is the name of the function. */
1887 static char *
1888 func_call (char *o, char **argv, const char *funcname)
1890 static int max_args = 0;
1891 char *fname;
1892 char *cp;
1893 char *body;
1894 int flen;
1895 int i;
1896 int saved_args;
1897 const struct function_table_entry *entry_p;
1898 struct variable *v;
1900 /* There is no way to define a variable with a space in the name, so strip
1901 leading and trailing whitespace as a favor to the user. */
1902 fname = argv[0];
1903 while (*fname != '\0' && isspace ((unsigned char)*fname))
1904 ++fname;
1906 cp = fname + strlen (fname) - 1;
1907 while (cp > fname && isspace ((unsigned char)*cp))
1908 --cp;
1909 cp[1] = '\0';
1911 /* Calling nothing is a no-op */
1912 if (*fname == '\0')
1913 return o;
1915 /* Are we invoking a builtin function? */
1917 entry_p = lookup_function (fname);
1919 if (entry_p)
1921 /* How many arguments do we have? */
1922 for (i=0; argv[i+1]; ++i)
1925 return expand_builtin_function (o, i, argv+1, entry_p);
1928 /* Not a builtin, so the first argument is the name of a variable to be
1929 expanded and interpreted as a function. Find it. */
1930 flen = strlen (fname);
1932 v = lookup_variable (fname, flen);
1934 if (v == 0)
1935 warn_undefined (fname, flen);
1937 if (v == 0 || *v->value == '\0')
1938 return o;
1940 body = (char *) alloca (flen + 4);
1941 body[0] = '$';
1942 body[1] = '(';
1943 memcpy (body + 2, fname, flen);
1944 body[flen+2] = ')';
1945 body[flen+3] = '\0';
1947 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
1949 push_new_variable_scope ();
1951 for (i=0; *argv; ++i, ++argv)
1953 char num[11];
1955 sprintf (num, "%d", i);
1956 define_variable (num, strlen (num), *argv, o_automatic, 0);
1959 /* If the number of arguments we have is < max_args, it means we're inside
1960 a recursive invocation of $(call ...). Fill in the remaining arguments
1961 in the new scope with the empty value, to hide them from this
1962 invocation. */
1964 for (; i < max_args; ++i)
1966 char num[11];
1968 sprintf (num, "%d", i);
1969 define_variable (num, strlen (num), "", o_automatic, 0);
1972 /* Expand the body in the context of the arguments, adding the result to
1973 the variable buffer. */
1975 v->exp_count = EXP_COUNT_MAX;
1977 saved_args = max_args;
1978 max_args = i;
1979 o = variable_expand_string (o, body, flen+3);
1980 max_args = saved_args;
1982 v->exp_count = 0;
1984 pop_variable_scope ();
1986 return o + strlen (o);
1989 void
1990 hash_init_function_table (void)
1992 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
1993 function_table_entry_hash_1, function_table_entry_hash_2,
1994 function_table_entry_hash_cmp);
1995 hash_load (&function_table, function_table_init,
1996 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));