Fix bug #1744: mask extra arguments to recursive invocations of $(call ...)
[make.git] / function.c
bloba6a04d49af30bf2aeacd3077cc8b264bbdb1ce49
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 char *
677 strip_whitespace (char **begpp, char **endpp)
679 while (isspace ((unsigned char)**begpp) && *begpp <= *endpp)
680 (*begpp) ++;
681 while (isspace ((unsigned char)**endpp) && *endpp >= *begpp)
682 (*endpp) --;
683 return *begpp;
687 is_numeric (char *p)
689 char *end = p + strlen (p) - 1;
690 char *beg = p;
691 strip_whitespace (&p, &end);
693 while (p <= end)
694 if (!ISDIGIT (*(p++))) /* ISDIGIT only evals its arg once: see make.h. */
695 return 0;
697 return (end - beg >= 0);
700 void
701 check_numeric (char *s, char *message)
703 if (!is_numeric (s))
704 fatal (reading_file, message);
709 static char *
710 func_word (char *o, char **argv, const char *funcname)
712 char *end_p=0;
713 int i=0;
714 char *p=0;
716 /* Check the first argument. */
717 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
718 i = atoi (argv[0]);
720 if (i == 0)
721 fatal (reading_file, _("first argument to `word' function must be greater than 0"));
724 end_p = argv[1];
725 while ((p = find_next_token (&end_p, 0)) != 0)
726 if (--i == 0)
727 break;
729 if (i == 0)
730 o = variable_buffer_output (o, p, end_p - p);
732 return o;
735 static char *
736 func_wordlist (char *o, char **argv, const char *funcname)
738 int start, count;
740 /* Check the arguments. */
741 check_numeric (argv[0],
742 _("non-numeric first argument to `wordlist' function"));
743 check_numeric (argv[1],
744 _("non-numeric second argument to `wordlist' function"));
746 start = atoi (argv[0]);
747 count = atoi (argv[1]) - start + 1;
749 if (count > 0)
751 char *p;
752 char *end_p = argv[2];
754 /* Find the beginning of the "start"th word. */
755 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
758 if (p)
760 /* Find the end of the "count"th word from start. */
761 while (--count && (find_next_token (&end_p, 0) != 0))
764 /* Return the stuff in the middle. */
765 o = variable_buffer_output (o, p, end_p - p);
769 return o;
772 static char*
773 func_findstring (char *o, char **argv, const char *funcname)
775 /* Find the first occurrence of the first string in the second. */
776 int i = strlen (argv[0]);
777 if (sindex (argv[1], 0, argv[0], i) != 0)
778 o = variable_buffer_output (o, argv[0], i);
780 return o;
783 static char *
784 func_foreach (char *o, char **argv, const char *funcname)
786 /* expand only the first two. */
787 char *varname = expand_argument (argv[0], NULL);
788 char *list = expand_argument (argv[1], NULL);
789 char *body = argv[2];
791 int doneany = 0;
792 char *list_iterator = list;
793 char *p;
794 unsigned int len;
795 register struct variable *var;
797 push_new_variable_scope ();
798 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
800 /* loop through LIST, put the value in VAR and expand BODY */
801 while ((p = find_next_token (&list_iterator, &len)) != 0)
803 char *result = 0;
806 char save = p[len];
808 p[len] = '\0';
809 free (var->value);
810 var->value = (char *) xstrdup ((char*) p);
811 p[len] = save;
814 result = allocated_variable_expand (body);
816 o = variable_buffer_output (o, result, strlen (result));
817 o = variable_buffer_output (o, " ", 1);
818 doneany = 1;
819 free (result);
822 if (doneany)
823 /* Kill the last space. */
824 --o;
826 pop_variable_scope ();
827 free (varname);
828 free (list);
830 return o;
833 struct a_word
835 struct a_word *next;
836 struct a_word *chain;
837 char *str;
838 int length;
839 int matched;
842 static unsigned long
843 a_word_hash_1 (const void *key)
845 return_STRING_HASH_1 (((struct a_word const *) key)->str);
848 static unsigned long
849 a_word_hash_2 (const void *key)
851 return_STRING_HASH_2 (((struct a_word const *) key)->str);
854 static int
855 a_word_hash_cmp (const void *x, const void *y)
857 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
858 if (result)
859 return result;
860 return_STRING_COMPARE (((struct a_word const *) x)->str,
861 ((struct a_word const *) y)->str);
864 struct a_pattern
866 struct a_pattern *next;
867 char *str;
868 char *percent;
869 int length;
870 int save_c;
873 static char *
874 func_filter_filterout (char *o, char **argv, const char *funcname)
876 struct a_word *wordhead;
877 struct a_word **wordtail;
878 struct a_word *wp;
879 struct a_pattern *pathead;
880 struct a_pattern **pattail;
881 struct a_pattern *pp;
883 struct hash_table a_word_table;
884 int is_filter = streq (funcname, "filter");
885 char *pat_iterator = argv[0];
886 char *word_iterator = argv[1];
887 int literals = 0;
888 int words = 0;
889 int hashing = 0;
890 char *p;
891 unsigned int len;
893 /* Chop ARGV[0] up into patterns to match against the words. */
895 pattail = &pathead;
896 while ((p = find_next_token (&pat_iterator, &len)) != 0)
898 struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
900 *pattail = pat;
901 pattail = &pat->next;
903 if (*pat_iterator != '\0')
904 ++pat_iterator;
906 pat->str = p;
907 pat->length = len;
908 pat->save_c = p[len];
909 p[len] = '\0';
910 pat->percent = find_percent (p);
911 if (pat->percent == 0)
912 literals++;
914 *pattail = 0;
916 /* Chop ARGV[1] up into words to match against the patterns. */
918 wordtail = &wordhead;
919 while ((p = find_next_token (&word_iterator, &len)) != 0)
921 struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
923 *wordtail = word;
924 wordtail = &word->next;
926 if (*word_iterator != '\0')
927 ++word_iterator;
929 p[len] = '\0';
930 word->str = p;
931 word->length = len;
932 word->matched = 0;
933 word->chain = 0;
934 words++;
936 *wordtail = 0;
938 /* Only use a hash table if arg list lengths justifies the cost. */
939 hashing = (literals >= 2 && (literals * words) >= 10);
940 if (hashing)
942 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
943 for (wp = wordhead; wp != 0; wp = wp->next)
945 struct a_word *owp = hash_insert (&a_word_table, wp);
946 if (owp)
947 wp->chain = owp;
951 if (words)
953 int doneany = 0;
955 /* Run each pattern through the words, killing words. */
956 for (pp = pathead; pp != 0; pp = pp->next)
958 if (pp->percent)
959 for (wp = wordhead; wp != 0; wp = wp->next)
960 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
961 else if (hashing)
963 struct a_word a_word_key;
964 a_word_key.str = pp->str;
965 a_word_key.length = pp->length;
966 wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
967 while (wp)
969 wp->matched |= 1;
970 wp = wp->chain;
973 else
974 for (wp = wordhead; wp != 0; wp = wp->next)
975 wp->matched |= (wp->length == pp->length
976 && strneq (pp->str, wp->str, wp->length));
979 /* Output the words that matched (or didn't, for filter-out). */
980 for (wp = wordhead; wp != 0; wp = wp->next)
981 if (is_filter ? wp->matched : !wp->matched)
983 o = variable_buffer_output (o, wp->str, strlen (wp->str));
984 o = variable_buffer_output (o, " ", 1);
985 doneany = 1;
988 if (doneany)
989 /* Kill the last space. */
990 --o;
993 for (pp = pathead; pp != 0; pp = pp->next)
994 pp->str[pp->length] = pp->save_c;
996 if (hashing)
997 hash_free (&a_word_table, 0);
999 return o;
1003 static char *
1004 func_strip (char *o, char **argv, const char *funcname)
1006 char *p = argv[0];
1007 int doneany =0;
1009 while (*p != '\0')
1011 int i=0;
1012 char *word_start=0;
1014 while (isspace ((unsigned char)*p))
1015 ++p;
1016 word_start = p;
1017 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1019 if (!i)
1020 break;
1021 o = variable_buffer_output (o, word_start, i);
1022 o = variable_buffer_output (o, " ", 1);
1023 doneany = 1;
1026 if (doneany)
1027 /* Kill the last space. */
1028 --o;
1029 return o;
1033 Print a warning or fatal message.
1035 static char *
1036 func_error (char *o, char **argv, const char *funcname)
1038 char **argvp;
1039 char *msg, *p;
1040 int len;
1042 /* The arguments will be broken on commas. Rather than create yet
1043 another special case where function arguments aren't broken up,
1044 just create a format string that puts them back together. */
1045 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1046 len += strlen (*argvp) + 2;
1048 p = msg = (char *) alloca (len + 1);
1050 for (argvp=argv; argvp[1] != 0; ++argvp)
1052 strcpy (p, *argvp);
1053 p += strlen (*argvp);
1054 *(p++) = ',';
1055 *(p++) = ' ';
1057 strcpy (p, *argvp);
1059 if (*funcname == 'e')
1060 fatal (reading_file, "%s", msg);
1062 /* The warning function expands to the empty string. */
1063 error (reading_file, "%s", msg);
1065 return o;
1070 chop argv[0] into words, and sort them.
1072 static char *
1073 func_sort (char *o, char **argv, const char *funcname)
1075 char **words = 0;
1076 int nwords = 0;
1077 register int wordi = 0;
1079 /* Chop ARGV[0] into words and put them in WORDS. */
1080 char *t = argv[0];
1081 char *p;
1082 unsigned int len;
1083 int i;
1085 while ((p = find_next_token (&t, &len)) != 0)
1087 if (wordi >= nwords - 1)
1089 nwords = (2 * nwords) + 5;
1090 words = (char **) xrealloc ((char *) words,
1091 nwords * sizeof (char *));
1093 words[wordi++] = savestring (p, len);
1096 if (!wordi)
1097 return o;
1099 /* Now sort the list of words. */
1100 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1102 /* Now write the sorted list. */
1103 for (i = 0; i < wordi; ++i)
1105 len = strlen (words[i]);
1106 if (i == wordi - 1 || strlen (words[i + 1]) != len
1107 || strcmp (words[i], words[i + 1]))
1109 o = variable_buffer_output (o, words[i], len);
1110 o = variable_buffer_output (o, " ", 1);
1112 free (words[i]);
1114 /* Kill the last space. */
1115 --o;
1117 free (words);
1119 return o;
1123 $(if condition,true-part[,false-part])
1125 CONDITION is false iff it evaluates to an empty string. White
1126 space before and after condition are stripped before evaluation.
1128 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1129 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1130 you can use $(if ...) to create side-effects (with $(shell ...), for
1131 example).
1134 static char *
1135 func_if (char *o, char **argv, const char *funcname)
1137 char *begp = argv[0];
1138 char *endp = begp + strlen (argv[0]);
1139 int result = 0;
1141 /* Find the result of the condition: if we have a value, and it's not
1142 empty, the condition is true. If we don't have a value, or it's the
1143 empty string, then it's false. */
1145 strip_whitespace (&begp, &endp);
1147 if (begp < endp)
1149 char *expansion = expand_argument (begp, NULL);
1151 result = strlen (expansion);
1152 free (expansion);
1155 /* If the result is true (1) we want to eval the first argument, and if
1156 it's false (0) we want to eval the second. If the argument doesn't
1157 exist we do nothing, otherwise expand it and add to the buffer. */
1159 argv += 1 + !result;
1161 if (argv[0])
1163 char *expansion;
1165 expansion = expand_argument (argv[0], NULL);
1167 o = variable_buffer_output (o, expansion, strlen (expansion));
1169 free (expansion);
1172 return o;
1175 static char *
1176 func_wildcard (char *o, char **argv, const char *funcname)
1179 #ifdef _AMIGA
1180 o = wildcard_expansion (argv[0], o);
1181 #else
1182 char *p = string_glob (argv[0]);
1183 o = variable_buffer_output (o, p, strlen (p));
1184 #endif
1185 return o;
1189 $(eval <makefile string>)
1191 Always resolves to the empty string.
1193 Treat the arguments as a segment of makefile, and parse them.
1196 static char *
1197 func_eval (char *o, char **argv, const char *funcname)
1199 char *buf;
1200 unsigned int len;
1202 /* Eval the buffer. Pop the current variable buffer setting so that the
1203 eval'd code can use its own without conflicting. */
1205 install_variable_buffer (&buf, &len);
1207 eval_buffer (argv[0]);
1209 restore_variable_buffer (buf, len);
1211 return o;
1215 static char *
1216 func_value (char *o, char **argv, const char *funcname)
1218 /* Look up the variable. */
1219 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1221 /* Copy its value into the output buffer without expanding it. */
1222 if (v)
1223 o = variable_buffer_output (o, v->value, strlen(v->value));
1225 return o;
1229 \r is replaced on UNIX as well. Is this desirable?
1231 void
1232 fold_newlines (char *buffer, int *length)
1234 char *dst = buffer;
1235 char *src = buffer;
1236 char *last_nonnl = buffer -1;
1237 src[*length] = 0;
1238 for (; *src != '\0'; ++src)
1240 if (src[0] == '\r' && src[1] == '\n')
1241 continue;
1242 if (*src == '\n')
1244 *dst++ = ' ';
1246 else
1248 last_nonnl = dst;
1249 *dst++ = *src;
1252 *(++last_nonnl) = '\0';
1253 *length = last_nonnl - buffer;
1258 int shell_function_pid = 0, shell_function_completed;
1261 #ifdef WINDOWS32
1262 /*untested*/
1264 #include <windows.h>
1265 #include <io.h>
1266 #include "sub_proc.h"
1269 void
1270 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1272 SECURITY_ATTRIBUTES saAttr;
1273 HANDLE hIn;
1274 HANDLE hErr;
1275 HANDLE hChildOutRd;
1276 HANDLE hChildOutWr;
1277 HANDLE hProcess;
1280 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1281 saAttr.bInheritHandle = TRUE;
1282 saAttr.lpSecurityDescriptor = NULL;
1284 if (DuplicateHandle (GetCurrentProcess(),
1285 GetStdHandle(STD_INPUT_HANDLE),
1286 GetCurrentProcess(),
1287 &hIn,
1289 TRUE,
1290 DUPLICATE_SAME_ACCESS) == FALSE) {
1291 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1292 GetLastError());
1295 if (DuplicateHandle(GetCurrentProcess(),
1296 GetStdHandle(STD_ERROR_HANDLE),
1297 GetCurrentProcess(),
1298 &hErr,
1300 TRUE,
1301 DUPLICATE_SAME_ACCESS) == FALSE) {
1302 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1303 GetLastError());
1306 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1307 fatal (NILF, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1309 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1311 if (!hProcess)
1312 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1314 /* make sure that CreateProcess() has Path it needs */
1315 sync_Path_environment();
1317 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1318 /* register process for wait */
1319 process_register(hProcess);
1321 /* set the pid for returning to caller */
1322 *pid_p = (int) hProcess;
1324 /* set up to read data from child */
1325 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1327 /* this will be closed almost right away */
1328 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1329 } else {
1330 /* reap/cleanup the failed process */
1331 process_cleanup(hProcess);
1333 /* close handles which were duplicated, they weren't used */
1334 CloseHandle(hIn);
1335 CloseHandle(hErr);
1337 /* close pipe handles, they won't be used */
1338 CloseHandle(hChildOutRd);
1339 CloseHandle(hChildOutWr);
1341 /* set status for return */
1342 pipedes[0] = pipedes[1] = -1;
1343 *pid_p = -1;
1346 #endif
1349 #ifdef __MSDOS__
1350 FILE *
1351 msdos_openpipe (int* pipedes, int *pidp, char *text)
1353 FILE *fpipe=0;
1354 /* MSDOS can't fork, but it has `popen'. */
1355 struct variable *sh = lookup_variable ("SHELL", 5);
1356 int e;
1357 extern int dos_command_running, dos_status;
1359 /* Make sure not to bother processing an empty line. */
1360 while (isblank ((unsigned char)*text))
1361 ++text;
1362 if (*text == '\0')
1363 return 0;
1365 if (sh)
1367 char buf[PATH_MAX + 7];
1368 /* This makes sure $SHELL value is used by $(shell), even
1369 though the target environment is not passed to it. */
1370 sprintf (buf, "SHELL=%s", sh->value);
1371 putenv (buf);
1374 e = errno;
1375 errno = 0;
1376 dos_command_running = 1;
1377 dos_status = 0;
1378 /* If dos_status becomes non-zero, it means the child process
1379 was interrupted by a signal, like SIGINT or SIGQUIT. See
1380 fatal_error_signal in commands.c. */
1381 fpipe = popen (text, "rt");
1382 dos_command_running = 0;
1383 if (!fpipe || dos_status)
1385 pipedes[0] = -1;
1386 *pidp = -1;
1387 if (dos_status)
1388 errno = EINTR;
1389 else if (errno == 0)
1390 errno = ENOMEM;
1391 shell_function_completed = -1;
1393 else
1395 pipedes[0] = fileno (fpipe);
1396 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1397 errno = e;
1398 shell_function_completed = 1;
1400 return fpipe;
1402 #endif
1405 Do shell spawning, with the naughty bits for different OSes.
1408 #ifdef VMS
1410 /* VMS can't do $(shell ...) */
1411 #define func_shell 0
1413 #else
1414 #ifndef _AMIGA
1415 static char *
1416 func_shell (char *o, char **argv, const char *funcname)
1418 char* batch_filename = NULL;
1419 int i;
1421 #ifdef __MSDOS__
1422 FILE *fpipe;
1423 #endif
1424 char **command_argv;
1425 char *error_prefix;
1426 char **envp;
1427 int pipedes[2];
1428 int pid;
1430 #ifndef __MSDOS__
1431 /* Construct the argument list. */
1432 command_argv = construct_command_argv (argv[0],
1433 (char **) NULL, (struct file *) 0,
1434 &batch_filename);
1435 if (command_argv == 0)
1436 return o;
1437 #endif
1439 /* Using a target environment for `shell' loses in cases like:
1440 export var = $(shell echo foobie)
1441 because target_environment hits a loop trying to expand $(var)
1442 to put it in the environment. This is even more confusing when
1443 var was not explicitly exported, but just appeared in the
1444 calling environment. */
1446 envp = environ;
1448 /* For error messages. */
1449 if (reading_file != 0)
1451 error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1452 sprintf (error_prefix,
1453 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1455 else
1456 error_prefix = "";
1458 #ifdef WINDOWS32
1459 windows32_openpipe (pipedes, &pid, command_argv, envp);
1461 if (pipedes[0] < 0) {
1462 /* open of the pipe failed, mark as failed execution */
1463 shell_function_completed = -1;
1465 return o;
1466 } else
1467 #else /* WINDOWS32 */
1469 # ifdef __MSDOS__
1470 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1471 if (pipedes[0] < 0)
1473 perror_with_name (error_prefix, "pipe");
1474 return o;
1476 # else
1477 if (pipe (pipedes) < 0)
1479 perror_with_name (error_prefix, "pipe");
1480 return o;
1483 pid = vfork ();
1484 if (pid < 0)
1485 perror_with_name (error_prefix, "fork");
1486 else if (pid == 0)
1487 child_execute_job (0, pipedes[1], command_argv, envp);
1488 else
1489 # endif /* ! __MSDOS__ */
1491 #endif /* WINDOWS32 */
1493 /* We are the parent. */
1495 char *buffer;
1496 unsigned int maxlen;
1497 int cc;
1499 /* Record the PID for reap_children. */
1500 shell_function_pid = pid;
1501 #ifndef __MSDOS__
1502 shell_function_completed = 0;
1504 /* Free the storage only the child needed. */
1505 free (command_argv[0]);
1506 free ((char *) command_argv);
1508 /* Close the write side of the pipe. */
1509 (void) close (pipedes[1]);
1510 #endif
1512 /* Set up and read from the pipe. */
1514 maxlen = 200;
1515 buffer = (char *) xmalloc (maxlen + 1);
1517 /* Read from the pipe until it gets EOF. */
1518 for (i = 0; ; i += cc)
1520 if (i == maxlen)
1522 maxlen += 512;
1523 buffer = (char *) xrealloc (buffer, maxlen + 1);
1526 cc = read (pipedes[0], &buffer[i], maxlen - i);
1527 if (cc <= 0)
1528 break;
1530 buffer[i] = '\0';
1532 /* Close the read side of the pipe. */
1533 #ifdef __MSDOS__
1534 if (fpipe)
1535 (void) pclose (fpipe);
1536 #else
1537 (void) close (pipedes[0]);
1538 #endif
1540 /* Loop until child_handler sets shell_function_completed
1541 to the status of our child shell. */
1542 while (shell_function_completed == 0)
1543 reap_children (1, 0);
1545 if (batch_filename) {
1546 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1547 batch_filename));
1548 remove (batch_filename);
1549 free (batch_filename);
1551 shell_function_pid = 0;
1553 /* The child_handler function will set shell_function_completed
1554 to 1 when the child dies normally, or to -1 if it
1555 dies with status 127, which is most likely an exec fail. */
1557 if (shell_function_completed == -1)
1559 /* This most likely means that the execvp failed,
1560 so we should just write out the error message
1561 that came in over the pipe from the child. */
1562 fputs (buffer, stderr);
1563 fflush (stderr);
1565 else
1567 /* The child finished normally. Replace all
1568 newlines in its output with spaces, and put
1569 that in the variable output buffer. */
1570 fold_newlines (buffer, &i);
1571 o = variable_buffer_output (o, buffer, i);
1574 free (buffer);
1577 return o;
1580 #else /* _AMIGA */
1582 /* Do the Amiga version of func_shell. */
1584 static char *
1585 func_shell (char *o, char **argv, const char *funcname)
1587 /* Amiga can't fork nor spawn, but I can start a program with
1588 redirection of my choice. However, this means that we
1589 don't have an opportunity to reopen stdout to trap it. Thus,
1590 we save our own stdout onto a new descriptor and dup a temp
1591 file's descriptor onto our stdout temporarily. After we
1592 spawn the shell program, we dup our own stdout back to the
1593 stdout descriptor. The buffer reading is the same as above,
1594 except that we're now reading from a file. */
1596 #include <dos/dos.h>
1597 #include <proto/dos.h>
1599 BPTR child_stdout;
1600 char tmp_output[FILENAME_MAX];
1601 unsigned int maxlen = 200;
1602 int cc, i;
1603 char * buffer, * ptr;
1604 char ** aptr;
1605 int len = 0;
1606 char* batch_filename = NULL;
1608 /* Construct the argument list. */
1609 command_argv = construct_command_argv (argv[0], (char **) NULL,
1610 (struct file *) 0, &batch_filename);
1611 if (command_argv == 0)
1612 return o;
1614 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1615 Ideally we would use main.c:open_tmpfile(), but this uses a special
1616 Open(), not fopen(), and I'm not familiar enough with the code to mess
1617 with it. */
1618 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1619 mktemp (tmp_output);
1620 child_stdout = Open (tmp_output, MODE_NEWFILE);
1622 for (aptr=command_argv; *aptr; aptr++)
1623 len += strlen (*aptr) + 1;
1625 buffer = xmalloc (len + 1);
1626 ptr = buffer;
1628 for (aptr=command_argv; *aptr; aptr++)
1630 strcpy (ptr, *aptr);
1631 ptr += strlen (ptr) + 1;
1632 *ptr ++ = ' ';
1633 *ptr = 0;
1636 ptr[-1] = '\n';
1638 Execute (buffer, NULL, child_stdout);
1639 free (buffer);
1641 Close (child_stdout);
1643 child_stdout = Open (tmp_output, MODE_OLDFILE);
1645 buffer = xmalloc (maxlen);
1646 i = 0;
1649 if (i == maxlen)
1651 maxlen += 512;
1652 buffer = (char *) xrealloc (buffer, maxlen + 1);
1655 cc = Read (child_stdout, &buffer[i], maxlen - i);
1656 if (cc > 0)
1657 i += cc;
1658 } while (cc > 0);
1660 Close (child_stdout);
1662 fold_newlines (buffer, &i);
1663 o = variable_buffer_output (o, buffer, i);
1664 free (buffer);
1665 return o;
1667 #endif /* _AMIGA */
1668 #endif /* !VMS */
1670 #ifdef EXPERIMENTAL
1673 equality. Return is string-boolean, ie, the empty string is false.
1675 static char *
1676 func_eq (char* o, char **argv, char *funcname)
1678 int result = ! strcmp (argv[0], argv[1]);
1679 o = variable_buffer_output (o, result ? "1" : "", result);
1680 return o;
1685 string-boolean not operator.
1687 static char *
1688 func_not (char* o, char **argv, char *funcname)
1690 char * s = argv[0];
1691 int result = 0;
1692 while (isspace ((unsigned char)*s))
1693 s++;
1694 result = ! (*s);
1695 o = variable_buffer_output (o, result ? "1" : "", result);
1696 return o;
1698 #endif
1701 /* Lookup table for builtin functions.
1703 This doesn't have to be sorted; we use a straight lookup. We might gain
1704 some efficiency by moving most often used functions to the start of the
1705 table.
1707 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1708 comma-separated values are treated as arguments.
1710 EXPAND_ARGS means that all arguments should be expanded before invocation.
1711 Functions that do namespace tricks (foreach) don't automatically expand. */
1713 static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
1716 static struct function_table_entry function_table_init[] =
1718 /* Name/size */ /* MIN MAX EXP? Function */
1719 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
1720 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
1721 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
1722 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
1723 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
1724 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
1725 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
1726 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
1727 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
1728 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
1729 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
1730 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
1731 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
1732 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
1733 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
1734 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
1735 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
1736 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
1737 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
1738 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
1739 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
1740 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
1741 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
1742 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
1743 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
1744 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
1745 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
1746 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
1747 #ifdef EXPERIMENTAL
1748 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
1749 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
1750 #endif
1753 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1756 /* These must come after the definition of function_table. */
1758 static char *
1759 expand_builtin_function (char *o, int argc, char **argv,
1760 const struct function_table_entry *entry_p)
1762 if (argc < (int)entry_p->minimum_args)
1763 fatal (reading_file,
1764 _("Insufficient number of arguments (%d) to function `%s'"),
1765 argc, entry_p->name);
1767 /* I suppose technically some function could do something with no
1768 arguments, but so far none do, so just test it for all functions here
1769 rather than in each one. We can change it later if necessary. */
1771 if (!argc)
1772 return o;
1774 if (!entry_p->func_ptr)
1775 fatal (reading_file, _("Unimplemented on this platform: function `%s'"),
1776 entry_p->name);
1778 return entry_p->func_ptr (o, argv, entry_p->name);
1781 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1782 opening ( or { and is not null-terminated. If a function invocation
1783 is found, expand it into the buffer at *OP, updating *OP, incrementing
1784 *STRINGP past the reference and returning nonzero. If not, return zero. */
1787 handle_function (char **op, char **stringp)
1789 const struct function_table_entry *entry_p;
1790 char openparen = (*stringp)[0];
1791 char closeparen = openparen == '(' ? ')' : '}';
1792 char *beg;
1793 char *end;
1794 int count = 0;
1795 register char *p;
1796 char **argv, **argvp;
1797 int nargs;
1799 beg = *stringp + 1;
1801 entry_p = lookup_function (beg);
1803 if (!entry_p)
1804 return 0;
1806 /* We found a builtin function. Find the beginning of its arguments (skip
1807 whitespace after the name). */
1809 beg = next_token (beg + entry_p->len);
1811 /* Find the end of the function invocation, counting nested use of
1812 whichever kind of parens we use. Since we're looking, count commas
1813 to get a rough estimate of how many arguments we might have. The
1814 count might be high, but it'll never be low. */
1816 for (nargs=1, end=beg; *end != '\0'; ++end)
1817 if (*end == ',')
1818 ++nargs;
1819 else if (*end == openparen)
1820 ++count;
1821 else if (*end == closeparen && --count < 0)
1822 break;
1824 if (count >= 0)
1825 fatal (reading_file,
1826 _("unterminated call to function `%s': missing `%c'"),
1827 entry_p->name, closeparen);
1829 *stringp = end;
1831 /* Get some memory to store the arg pointers. */
1832 argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
1834 /* Chop the string into arguments, then a nul. As soon as we hit
1835 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1836 last argument.
1838 If we're expanding, store pointers to the expansion of each one. If
1839 not, make a duplicate of the string and point into that, nul-terminating
1840 each argument. */
1842 if (!entry_p->expand_args)
1844 int len = end - beg;
1846 p = xmalloc (len+1);
1847 memcpy (p, beg, len);
1848 p[len] = '\0';
1849 beg = p;
1850 end = beg + len;
1853 for (p=beg, nargs=0; p <= end; ++argvp)
1855 char *next;
1857 ++nargs;
1859 if (nargs == entry_p->maximum_args
1860 || (! (next = find_next_argument (openparen, closeparen, p, end))))
1861 next = end;
1863 if (entry_p->expand_args)
1864 *argvp = expand_argument (p, next);
1865 else
1867 *argvp = p;
1868 *next = '\0';
1871 p = next + 1;
1873 *argvp = NULL;
1875 /* Finally! Run the function... */
1876 *op = expand_builtin_function (*op, nargs, argv, entry_p);
1878 /* Free memory. */
1879 if (entry_p->expand_args)
1880 for (argvp=argv; *argvp != 0; ++argvp)
1881 free (*argvp);
1882 else
1883 free (beg);
1885 return 1;
1889 /* User-defined functions. Expand the first argument as either a builtin
1890 function or a make variable, in the context of the rest of the arguments
1891 assigned to $1, $2, ... $N. $0 is the name of the function. */
1893 static char *
1894 func_call (char *o, char **argv, const char *funcname)
1896 static int max_args = 0;
1897 char *fname;
1898 char *cp;
1899 char *body;
1900 int flen;
1901 int i;
1902 int saved_args;
1903 const struct function_table_entry *entry_p;
1904 struct variable *v;
1906 /* There is no way to define a variable with a space in the name, so strip
1907 leading and trailing whitespace as a favor to the user. */
1908 fname = argv[0];
1909 while (*fname != '\0' && isspace ((unsigned char)*fname))
1910 ++fname;
1912 cp = fname + strlen (fname) - 1;
1913 while (cp > fname && isspace ((unsigned char)*cp))
1914 --cp;
1915 cp[1] = '\0';
1917 /* Calling nothing is a no-op */
1918 if (*fname == '\0')
1919 return o;
1921 /* Are we invoking a builtin function? */
1923 entry_p = lookup_function (fname);
1925 if (entry_p)
1927 /* How many arguments do we have? */
1928 for (i=0; argv[i+1]; ++i)
1931 return expand_builtin_function (o, i, argv+1, entry_p);
1934 /* Not a builtin, so the first argument is the name of a variable to be
1935 expanded and interpreted as a function. Find it. */
1936 flen = strlen (fname);
1938 v = lookup_variable (fname, flen);
1940 if (v == 0)
1941 warn_undefined (fname, flen);
1943 if (v == 0 || *v->value == '\0')
1944 return o;
1946 body = (char *) alloca (flen + 4);
1947 body[0] = '$';
1948 body[1] = '(';
1949 memcpy (body + 2, fname, flen);
1950 body[flen+2] = ')';
1951 body[flen+3] = '\0';
1953 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
1955 push_new_variable_scope ();
1957 for (i=0; *argv; ++i, ++argv)
1959 char num[11];
1961 sprintf (num, "%d", i);
1962 define_variable (num, strlen (num), *argv, o_automatic, 0);
1965 /* If the number of arguments we have is < max_args, it means we're inside
1966 a recursive invocation of $(call ...). Fill in the remaining arguments
1967 in the new scope with the empty value, to hide them from this
1968 invocation. */
1970 for (; i < max_args; ++i)
1972 char num[11];
1974 sprintf (num, "%d", i);
1975 define_variable (num, strlen (num), "", o_automatic, 0);
1978 /* Expand the body in the context of the arguments, adding the result to
1979 the variable buffer. */
1981 v->exp_count = EXP_COUNT_MAX;
1983 saved_args = max_args;
1984 max_args = i;
1985 o = variable_expand_string (o, body, flen+3);
1986 max_args = saved_args;
1988 v->exp_count = 0;
1990 pop_variable_scope ();
1992 return o + strlen (o);
1995 void
1996 hash_init_function_table (void)
1998 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
1999 function_table_entry_hash_1, function_table_entry_hash_2,
2000 function_table_entry_hash_cmp);
2001 hash_load (&function_table, function_table_init,
2002 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));