Fix bug #2892.
[make.git] / function.c
blob08a4d569181bbf94eb68931f21226ab557f57860
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 char *t = text;
84 unsigned int tlen = strlen (text);
85 char *p;
87 if (slen == 0 && !by_word && !suffix_only)
89 /* The first occurrence of "" in any string is its end. */
90 o = variable_buffer_output (o, t, tlen);
91 if (rlen > 0)
92 o = variable_buffer_output (o, replace, rlen);
93 return o;
98 if ((by_word | suffix_only) && slen == 0)
99 /* When matching by words, the empty string should match
100 the end of each word, rather than the end of the whole text. */
101 p = end_of_token (next_token (t));
102 else
104 p = sindex (t, tlen, subst, slen);
105 if (p == 0)
107 /* No more matches. Output everything left on the end. */
108 o = variable_buffer_output (o, t, tlen);
109 return o;
113 /* Output everything before this occurrence of the string to replace. */
114 if (p > t)
115 o = variable_buffer_output (o, t, p - t);
117 /* If we're substituting only by fully matched words,
118 or only at the ends of words, check that this case qualifies. */
119 if ((by_word
120 && ((p > t && !isblank ((unsigned char)p[-1]))
121 || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
122 || (suffix_only
123 && (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
124 /* Struck out. Output the rest of the string that is
125 no longer to be replaced. */
126 o = variable_buffer_output (o, subst, slen);
127 else if (rlen > 0)
128 /* Output the replacement string. */
129 o = variable_buffer_output (o, replace, rlen);
131 /* Advance T past the string to be replaced; adjust tlen. */
133 char *nt = p + slen;
134 tlen -= nt - t;
135 t = nt;
137 } while (*t != '\0');
139 return o;
143 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
144 and replacing strings matching PATTERN with REPLACE.
145 If PATTERN_PERCENT is not nil, PATTERN has already been
146 run through find_percent, and PATTERN_PERCENT is the result.
147 If REPLACE_PERCENT is not nil, REPLACE has already been
148 run through find_percent, and REPLACE_PERCENT is the result. */
150 char *
151 patsubst_expand (char *o, char *text, char *pattern, char *replace,
152 char *pattern_percent, char *replace_percent)
154 unsigned int pattern_prepercent_len, pattern_postpercent_len;
155 unsigned int replace_prepercent_len, replace_postpercent_len = 0;
156 char *t;
157 unsigned int len;
158 int doneany = 0;
160 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
161 will be collapsed before we call subst_expand if PATTERN has no %. */
162 if (replace_percent == 0)
163 replace_percent = find_percent (replace);
164 if (replace_percent != 0)
166 /* Record the length of REPLACE before and after the % so
167 we don't have to compute these lengths more than once. */
168 replace_prepercent_len = replace_percent - replace;
169 replace_postpercent_len = strlen (replace_percent + 1);
171 else
172 /* We store the length of the replacement
173 so we only need to compute it once. */
174 replace_prepercent_len = strlen (replace);
176 if (pattern_percent == 0)
177 pattern_percent = find_percent (pattern);
178 if (pattern_percent == 0)
179 /* With no % in the pattern, this is just a simple substitution. */
180 return subst_expand (o, text, pattern, replace,
181 strlen (pattern), strlen (replace), 1, 0);
183 /* Record the length of PATTERN before and after the %
184 so we don't have to compute it more than once. */
185 pattern_prepercent_len = pattern_percent - pattern;
186 pattern_postpercent_len = strlen (pattern_percent + 1);
188 while ((t = find_next_token (&text, &len)) != 0)
190 int fail = 0;
192 /* Is it big enough to match? */
193 if (len < pattern_prepercent_len + pattern_postpercent_len)
194 fail = 1;
196 /* Does the prefix match? */
197 if (!fail && pattern_prepercent_len > 0
198 && (*t != *pattern
199 || t[pattern_prepercent_len - 1] != pattern_percent[-1]
200 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
201 fail = 1;
203 /* Does the suffix match? */
204 if (!fail && pattern_postpercent_len > 0
205 && (t[len - 1] != pattern_percent[pattern_postpercent_len]
206 || t[len - pattern_postpercent_len] != pattern_percent[1]
207 || !strneq (&t[len - pattern_postpercent_len],
208 &pattern_percent[1], pattern_postpercent_len - 1)))
209 fail = 1;
211 if (fail)
212 /* It didn't match. Output the string. */
213 o = variable_buffer_output (o, t, len);
214 else
216 /* It matched. Output the replacement. */
218 /* Output the part of the replacement before the %. */
219 o = variable_buffer_output (o, replace, replace_prepercent_len);
221 if (replace_percent != 0)
223 /* Output the part of the matched string that
224 matched the % in the pattern. */
225 o = variable_buffer_output (o, t + pattern_prepercent_len,
226 len - (pattern_prepercent_len
227 + pattern_postpercent_len));
228 /* Output the part of the replacement after the %. */
229 o = variable_buffer_output (o, replace_percent + 1,
230 replace_postpercent_len);
234 /* Output a space, but not if the replacement is "". */
235 if (fail || replace_prepercent_len > 0
236 || (replace_percent != 0 && len + replace_postpercent_len > 0))
238 o = variable_buffer_output (o, " ", 1);
239 doneany = 1;
242 if (doneany)
243 /* Kill the last space. */
244 --o;
246 return o;
250 /* Look up a function by name. */
252 static const struct function_table_entry *
253 lookup_function (const char *s)
255 const char *e = s;
257 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
258 e++;
259 if (*e == '\0' || isblank ((unsigned char) *e))
261 struct function_table_entry function_table_entry_key;
262 function_table_entry_key.name = s;
263 function_table_entry_key.len = e - s;
265 return hash_find_item (&function_table, &function_table_entry_key);
267 return 0;
271 /* Return 1 if PATTERN matches STR, 0 if not. */
274 pattern_matches (char *pattern, char *percent, char *str)
276 unsigned int sfxlen, strlength;
278 if (percent == 0)
280 unsigned int len = strlen (pattern) + 1;
281 char *new_chars = (char *) alloca (len);
282 bcopy (pattern, new_chars, len);
283 pattern = new_chars;
284 percent = find_percent (pattern);
285 if (percent == 0)
286 return streq (pattern, str);
289 sfxlen = strlen (percent + 1);
290 strlength = strlen (str);
292 if (strlength < (percent - pattern) + sfxlen
293 || !strneq (pattern, str, percent - pattern))
294 return 0;
296 return !strcmp (percent + 1, str + (strlength - sfxlen));
300 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
301 ENDPARENtheses), starting at PTR before END. Return a pointer to
302 next character.
304 If no next argument is found, return NULL.
307 static char *
308 find_next_argument (char startparen, char endparen,
309 const char *ptr, const char *end)
311 int count = 0;
313 for (; ptr < end; ++ptr)
314 if (*ptr == startparen)
315 ++count;
317 else if (*ptr == endparen)
319 --count;
320 if (count < 0)
321 return NULL;
324 else if (*ptr == ',' && !count)
325 return (char *)ptr;
327 /* We didn't find anything. */
328 return NULL;
332 /* Glob-expand LINE. The returned pointer is
333 only good until the next call to string_glob. */
335 static char *
336 string_glob (char *line)
338 static char *result = 0;
339 static unsigned int length;
340 register struct nameseq *chain;
341 register unsigned int idx;
343 chain = multi_glob (parse_file_seq
344 (&line, '\0', sizeof (struct nameseq),
345 /* We do not want parse_file_seq to strip `./'s.
346 That would break examples like:
347 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
349 sizeof (struct nameseq));
351 if (result == 0)
353 length = 100;
354 result = (char *) xmalloc (100);
357 idx = 0;
358 while (chain != 0)
360 register char *name = chain->name;
361 unsigned int len = strlen (name);
363 struct nameseq *next = chain->next;
364 free ((char *) chain);
365 chain = next;
367 /* multi_glob will pass names without globbing metacharacters
368 through as is, but we want only files that actually exist. */
369 if (file_exists_p (name))
371 if (idx + len + 1 > length)
373 length += (len + 1) * 2;
374 result = (char *) xrealloc (result, length);
376 bcopy (name, &result[idx], len);
377 idx += len;
378 result[idx++] = ' ';
381 free (name);
384 /* Kill the last space and terminate the string. */
385 if (idx == 0)
386 result[0] = '\0';
387 else
388 result[idx - 1] = '\0';
390 return result;
394 Builtin functions
397 static char *
398 func_patsubst (char *o, char **argv, const char *funcname)
400 o = patsubst_expand (o, argv[2], argv[0], argv[1], (char *) 0, (char *) 0);
401 return o;
405 static char *
406 func_join (char *o, char **argv, const char *funcname)
408 int doneany = 0;
410 /* Write each word of the first argument directly followed
411 by the corresponding word of the second argument.
412 If the two arguments have a different number of words,
413 the excess words are just output separated by blanks. */
414 register char *tp;
415 register char *pp;
416 char *list1_iterator = argv[0];
417 char *list2_iterator = argv[1];
420 unsigned int len1, len2;
422 tp = find_next_token (&list1_iterator, &len1);
423 if (tp != 0)
424 o = variable_buffer_output (o, tp, len1);
426 pp = find_next_token (&list2_iterator, &len2);
427 if (pp != 0)
428 o = variable_buffer_output (o, pp, len2);
430 if (tp != 0 || pp != 0)
432 o = variable_buffer_output (o, " ", 1);
433 doneany = 1;
436 while (tp != 0 || pp != 0);
437 if (doneany)
438 /* Kill the last blank. */
439 --o;
441 return o;
445 static char *
446 func_origin (char *o, char **argv, const char *funcname)
448 /* Expand the argument. */
449 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
450 if (v == 0)
451 o = variable_buffer_output (o, "undefined", 9);
452 else
453 switch (v->origin)
455 default:
456 case o_invalid:
457 abort ();
458 break;
459 case o_default:
460 o = variable_buffer_output (o, "default", 7);
461 break;
462 case o_env:
463 o = variable_buffer_output (o, "environment", 11);
464 break;
465 case o_file:
466 o = variable_buffer_output (o, "file", 4);
467 break;
468 case o_env_override:
469 o = variable_buffer_output (o, "environment override", 20);
470 break;
471 case o_command:
472 o = variable_buffer_output (o, "command line", 12);
473 break;
474 case o_override:
475 o = variable_buffer_output (o, "override", 8);
476 break;
477 case o_automatic:
478 o = variable_buffer_output (o, "automatic", 9);
479 break;
482 return o;
485 #ifdef VMS
486 # define IS_PATHSEP(c) ((c) == ']')
487 #else
488 # ifdef HAVE_DOS_PATHS
489 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
490 # else
491 # define IS_PATHSEP(c) ((c) == '/')
492 # endif
493 #endif
496 static char *
497 func_notdir_suffix (char *o, char **argv, const char *funcname)
499 /* Expand the argument. */
500 char *list_iterator = argv[0];
501 char *p2 =0;
502 int doneany =0;
503 unsigned int len=0;
505 int is_suffix = streq (funcname, "suffix");
506 int is_notdir = !is_suffix;
507 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
509 char *p = p2 + len;
512 while (p >= p2 && (!is_suffix || *p != '.'))
514 if (IS_PATHSEP (*p))
515 break;
516 --p;
519 if (p >= p2)
521 if (is_notdir)
522 ++p;
523 else if (*p != '.')
524 continue;
525 o = variable_buffer_output (o, p, len - (p - p2));
527 #ifdef HAVE_DOS_PATHS
528 /* Handle the case of "d:foo/bar". */
529 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
531 p = p2 + 2;
532 o = variable_buffer_output (o, p, len - (p - p2));
534 #endif
535 else if (is_notdir)
536 o = variable_buffer_output (o, p2, len);
538 if (is_notdir || p >= p2)
540 o = variable_buffer_output (o, " ", 1);
541 doneany = 1;
544 if (doneany)
545 /* Kill last space. */
546 --o;
549 return o;
554 static char *
555 func_basename_dir (char *o, char **argv, const char *funcname)
557 /* Expand the argument. */
558 char *p3 = argv[0];
559 char *p2=0;
560 int doneany=0;
561 unsigned int len=0;
562 char *p=0;
563 int is_basename= streq (funcname, "basename");
564 int is_dir= !is_basename;
566 while ((p2 = find_next_token (&p3, &len)) != 0)
568 p = p2 + len;
569 while (p >= p2 && (!is_basename || *p != '.'))
571 if (IS_PATHSEP (*p))
572 break;
573 --p;
576 if (p >= p2 && (is_dir))
577 o = variable_buffer_output (o, p2, ++p - p2);
578 else if (p >= p2 && (*p == '.'))
579 o = variable_buffer_output (o, p2, p - p2);
580 #ifdef HAVE_DOS_PATHS
581 /* Handle the "d:foobar" case */
582 else if (p2[0] && p2[1] == ':' && is_dir)
583 o = variable_buffer_output (o, p2, 2);
584 #endif
585 else if (is_dir)
586 #ifdef VMS
587 o = variable_buffer_output (o, "[]", 2);
588 #else
589 #ifndef _AMIGA
590 o = variable_buffer_output (o, "./", 2);
591 #else
592 ; /* Just a nop... */
593 #endif /* AMIGA */
594 #endif /* !VMS */
595 else
596 /* The entire name is the basename. */
597 o = variable_buffer_output (o, p2, len);
599 o = variable_buffer_output (o, " ", 1);
600 doneany = 1;
602 if (doneany)
603 /* Kill last space. */
604 --o;
607 return o;
610 static char *
611 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
613 int fixlen = strlen (argv[0]);
614 char *list_iterator = argv[1];
615 int is_addprefix = streq (funcname, "addprefix");
616 int is_addsuffix = !is_addprefix;
618 int doneany = 0;
619 char *p;
620 unsigned int len;
622 while ((p = find_next_token (&list_iterator, &len)) != 0)
624 if (is_addprefix)
625 o = variable_buffer_output (o, argv[0], fixlen);
626 o = variable_buffer_output (o, p, len);
627 if (is_addsuffix)
628 o = variable_buffer_output (o, argv[0], fixlen);
629 o = variable_buffer_output (o, " ", 1);
630 doneany = 1;
633 if (doneany)
634 /* Kill last space. */
635 --o;
637 return o;
640 static char *
641 func_subst (char *o, char **argv, const char *funcname)
643 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
644 strlen (argv[1]), 0, 0);
646 return o;
650 static char *
651 func_firstword (char *o, char **argv, const char *funcname)
653 unsigned int i;
654 char *words = argv[0]; /* Use a temp variable for find_next_token */
655 char *p = find_next_token (&words, &i);
657 if (p != 0)
658 o = variable_buffer_output (o, p, i);
660 return o;
664 static char *
665 func_words (char *o, char **argv, const char *funcname)
667 int i = 0;
668 char *word_iterator = argv[0];
669 char buf[20];
671 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
672 ++i;
674 sprintf (buf, "%d", i);
675 o = variable_buffer_output (o, buf, strlen (buf));
678 return o;
681 static char *
682 strip_whitespace (const char **begpp, const char **endpp)
684 while (isspace ((unsigned char)**begpp) && *begpp <= *endpp)
685 (*begpp) ++;
686 while (isspace ((unsigned char)**endpp) && *endpp >= *begpp)
687 (*endpp) --;
688 return (char *)*begpp;
691 static void
692 check_numeric (const char *s, const char *message)
694 const char *end = s + strlen (s) - 1;
695 const char *beg = s;
696 strip_whitespace (&s, &end);
698 for (; s <= end; ++s)
699 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
700 break;
702 if (s <= end || end - beg < 0)
703 fatal (reading_file, "%s: '%s'", message, beg);
708 static char *
709 func_word (char *o, char **argv, const char *funcname)
711 char *end_p=0;
712 int i=0;
713 char *p=0;
715 /* Check the first argument. */
716 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
717 i = atoi (argv[0]);
719 if (i == 0)
720 fatal (reading_file, _("first argument to `word' function must be greater than 0"));
723 end_p = argv[1];
724 while ((p = find_next_token (&end_p, 0)) != 0)
725 if (--i == 0)
726 break;
728 if (i == 0)
729 o = variable_buffer_output (o, p, end_p - p);
731 return o;
734 static char *
735 func_wordlist (char *o, char **argv, const char *funcname)
737 int start, count;
739 /* Check the arguments. */
740 check_numeric (argv[0],
741 _("non-numeric first argument to `wordlist' function"));
742 check_numeric (argv[1],
743 _("non-numeric second argument to `wordlist' function"));
745 start = atoi (argv[0]);
746 count = atoi (argv[1]) - start + 1;
748 if (count > 0)
750 char *p;
751 char *end_p = argv[2];
753 /* Find the beginning of the "start"th word. */
754 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
757 if (p)
759 /* Find the end of the "count"th word from start. */
760 while (--count && (find_next_token (&end_p, 0) != 0))
763 /* Return the stuff in the middle. */
764 o = variable_buffer_output (o, p, end_p - p);
768 return o;
771 static char*
772 func_findstring (char *o, char **argv, const char *funcname)
774 /* Find the first occurrence of the first string in the second. */
775 int i = strlen (argv[0]);
776 if (sindex (argv[1], 0, argv[0], i) != 0)
777 o = variable_buffer_output (o, argv[0], i);
779 return o;
782 static char *
783 func_foreach (char *o, char **argv, const char *funcname)
785 /* expand only the first two. */
786 char *varname = expand_argument (argv[0], NULL);
787 char *list = expand_argument (argv[1], NULL);
788 char *body = argv[2];
790 int doneany = 0;
791 char *list_iterator = list;
792 char *p;
793 unsigned int len;
794 register struct variable *var;
796 push_new_variable_scope ();
797 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
799 /* loop through LIST, put the value in VAR and expand BODY */
800 while ((p = find_next_token (&list_iterator, &len)) != 0)
802 char *result = 0;
805 char save = p[len];
807 p[len] = '\0';
808 free (var->value);
809 var->value = (char *) xstrdup ((char*) p);
810 p[len] = save;
813 result = allocated_variable_expand (body);
815 o = variable_buffer_output (o, result, strlen (result));
816 o = variable_buffer_output (o, " ", 1);
817 doneany = 1;
818 free (result);
821 if (doneany)
822 /* Kill the last space. */
823 --o;
825 pop_variable_scope ();
826 free (varname);
827 free (list);
829 return o;
832 struct a_word
834 struct a_word *next;
835 struct a_word *chain;
836 char *str;
837 int length;
838 int matched;
841 static unsigned long
842 a_word_hash_1 (const void *key)
844 return_STRING_HASH_1 (((struct a_word const *) key)->str);
847 static unsigned long
848 a_word_hash_2 (const void *key)
850 return_STRING_HASH_2 (((struct a_word const *) key)->str);
853 static int
854 a_word_hash_cmp (const void *x, const void *y)
856 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
857 if (result)
858 return result;
859 return_STRING_COMPARE (((struct a_word const *) x)->str,
860 ((struct a_word const *) y)->str);
863 struct a_pattern
865 struct a_pattern *next;
866 char *str;
867 char *percent;
868 int length;
869 int save_c;
872 static char *
873 func_filter_filterout (char *o, char **argv, const char *funcname)
875 struct a_word *wordhead;
876 struct a_word **wordtail;
877 struct a_word *wp;
878 struct a_pattern *pathead;
879 struct a_pattern **pattail;
880 struct a_pattern *pp;
882 struct hash_table a_word_table;
883 int is_filter = streq (funcname, "filter");
884 char *pat_iterator = argv[0];
885 char *word_iterator = argv[1];
886 int literals = 0;
887 int words = 0;
888 int hashing = 0;
889 char *p;
890 unsigned int len;
892 /* Chop ARGV[0] up into patterns to match against the words. */
894 pattail = &pathead;
895 while ((p = find_next_token (&pat_iterator, &len)) != 0)
897 struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
899 *pattail = pat;
900 pattail = &pat->next;
902 if (*pat_iterator != '\0')
903 ++pat_iterator;
905 pat->str = p;
906 pat->length = len;
907 pat->save_c = p[len];
908 p[len] = '\0';
909 pat->percent = find_percent (p);
910 if (pat->percent == 0)
911 literals++;
913 *pattail = 0;
915 /* Chop ARGV[1] up into words to match against the patterns. */
917 wordtail = &wordhead;
918 while ((p = find_next_token (&word_iterator, &len)) != 0)
920 struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
922 *wordtail = word;
923 wordtail = &word->next;
925 if (*word_iterator != '\0')
926 ++word_iterator;
928 p[len] = '\0';
929 word->str = p;
930 word->length = len;
931 word->matched = 0;
932 word->chain = 0;
933 words++;
935 *wordtail = 0;
937 /* Only use a hash table if arg list lengths justifies the cost. */
938 hashing = (literals >= 2 && (literals * words) >= 10);
939 if (hashing)
941 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
942 for (wp = wordhead; wp != 0; wp = wp->next)
944 struct a_word *owp = hash_insert (&a_word_table, wp);
945 if (owp)
946 wp->chain = owp;
950 if (words)
952 int doneany = 0;
954 /* Run each pattern through the words, killing words. */
955 for (pp = pathead; pp != 0; pp = pp->next)
957 if (pp->percent)
958 for (wp = wordhead; wp != 0; wp = wp->next)
959 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
960 else if (hashing)
962 struct a_word a_word_key;
963 a_word_key.str = pp->str;
964 a_word_key.length = pp->length;
965 wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
966 while (wp)
968 wp->matched |= 1;
969 wp = wp->chain;
972 else
973 for (wp = wordhead; wp != 0; wp = wp->next)
974 wp->matched |= (wp->length == pp->length
975 && strneq (pp->str, wp->str, wp->length));
978 /* Output the words that matched (or didn't, for filter-out). */
979 for (wp = wordhead; wp != 0; wp = wp->next)
980 if (is_filter ? wp->matched : !wp->matched)
982 o = variable_buffer_output (o, wp->str, strlen (wp->str));
983 o = variable_buffer_output (o, " ", 1);
984 doneany = 1;
987 if (doneany)
988 /* Kill the last space. */
989 --o;
992 for (pp = pathead; pp != 0; pp = pp->next)
993 pp->str[pp->length] = pp->save_c;
995 if (hashing)
996 hash_free (&a_word_table, 0);
998 return o;
1002 static char *
1003 func_strip (char *o, char **argv, const char *funcname)
1005 char *p = argv[0];
1006 int doneany =0;
1008 while (*p != '\0')
1010 int i=0;
1011 char *word_start=0;
1013 while (isspace ((unsigned char)*p))
1014 ++p;
1015 word_start = p;
1016 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1018 if (!i)
1019 break;
1020 o = variable_buffer_output (o, word_start, i);
1021 o = variable_buffer_output (o, " ", 1);
1022 doneany = 1;
1025 if (doneany)
1026 /* Kill the last space. */
1027 --o;
1028 return o;
1032 Print a warning or fatal message.
1034 static char *
1035 func_error (char *o, char **argv, const char *funcname)
1037 char **argvp;
1038 char *msg, *p;
1039 int len;
1041 /* The arguments will be broken on commas. Rather than create yet
1042 another special case where function arguments aren't broken up,
1043 just create a format string that puts them back together. */
1044 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1045 len += strlen (*argvp) + 2;
1047 p = msg = (char *) alloca (len + 1);
1049 for (argvp=argv; argvp[1] != 0; ++argvp)
1051 strcpy (p, *argvp);
1052 p += strlen (*argvp);
1053 *(p++) = ',';
1054 *(p++) = ' ';
1056 strcpy (p, *argvp);
1058 if (*funcname == 'e')
1059 fatal (reading_file, "%s", msg);
1061 /* The warning function expands to the empty string. */
1062 error (reading_file, "%s", msg);
1064 return o;
1069 chop argv[0] into words, and sort them.
1071 static char *
1072 func_sort (char *o, char **argv, const char *funcname)
1074 char **words = 0;
1075 int nwords = 0;
1076 register int wordi = 0;
1078 /* Chop ARGV[0] into words and put them in WORDS. */
1079 char *t = argv[0];
1080 char *p;
1081 unsigned int len;
1082 int i;
1084 while ((p = find_next_token (&t, &len)) != 0)
1086 if (wordi >= nwords - 1)
1088 nwords = (2 * nwords) + 5;
1089 words = (char **) xrealloc ((char *) words,
1090 nwords * sizeof (char *));
1092 words[wordi++] = savestring (p, len);
1095 if (!wordi)
1096 return o;
1098 /* Now sort the list of words. */
1099 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1101 /* Now write the sorted list. */
1102 for (i = 0; i < wordi; ++i)
1104 len = strlen (words[i]);
1105 if (i == wordi - 1 || strlen (words[i + 1]) != len
1106 || strcmp (words[i], words[i + 1]))
1108 o = variable_buffer_output (o, words[i], len);
1109 o = variable_buffer_output (o, " ", 1);
1111 free (words[i]);
1113 /* Kill the last space. */
1114 --o;
1116 free (words);
1118 return o;
1122 $(if condition,true-part[,false-part])
1124 CONDITION is false iff it evaluates to an empty string. White
1125 space before and after condition are stripped before evaluation.
1127 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1128 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1129 you can use $(if ...) to create side-effects (with $(shell ...), for
1130 example).
1133 static char *
1134 func_if (char *o, char **argv, const char *funcname)
1136 const char *begp = argv[0];
1137 const char *endp = begp + strlen (argv[0]);
1138 int result = 0;
1140 /* Find the result of the condition: if we have a value, and it's not
1141 empty, the condition is true. If we don't have a value, or it's the
1142 empty string, then it's false. */
1144 strip_whitespace (&begp, &endp);
1146 if (begp < endp)
1148 char *expansion = expand_argument (begp, NULL);
1150 result = strlen (expansion);
1151 free (expansion);
1154 /* If the result is true (1) we want to eval the first argument, and if
1155 it's false (0) we want to eval the second. If the argument doesn't
1156 exist we do nothing, otherwise expand it and add to the buffer. */
1158 argv += 1 + !result;
1160 if (argv[0])
1162 char *expansion;
1164 expansion = expand_argument (argv[0], NULL);
1166 o = variable_buffer_output (o, expansion, strlen (expansion));
1168 free (expansion);
1171 return o;
1174 static char *
1175 func_wildcard (char *o, char **argv, const char *funcname)
1178 #ifdef _AMIGA
1179 o = wildcard_expansion (argv[0], o);
1180 #else
1181 char *p = string_glob (argv[0]);
1182 o = variable_buffer_output (o, p, strlen (p));
1183 #endif
1184 return o;
1188 $(eval <makefile string>)
1190 Always resolves to the empty string.
1192 Treat the arguments as a segment of makefile, and parse them.
1195 static char *
1196 func_eval (char *o, char **argv, const char *funcname)
1198 char *buf;
1199 unsigned int len;
1201 /* Eval the buffer. Pop the current variable buffer setting so that the
1202 eval'd code can use its own without conflicting. */
1204 install_variable_buffer (&buf, &len);
1206 eval_buffer (argv[0]);
1208 restore_variable_buffer (buf, len);
1210 return o;
1214 static char *
1215 func_value (char *o, char **argv, const char *funcname)
1217 /* Look up the variable. */
1218 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1220 /* Copy its value into the output buffer without expanding it. */
1221 if (v)
1222 o = variable_buffer_output (o, v->value, strlen(v->value));
1224 return o;
1228 \r is replaced on UNIX as well. Is this desirable?
1230 void
1231 fold_newlines (char *buffer, int *length)
1233 char *dst = buffer;
1234 char *src = buffer;
1235 char *last_nonnl = buffer -1;
1236 src[*length] = 0;
1237 for (; *src != '\0'; ++src)
1239 if (src[0] == '\r' && src[1] == '\n')
1240 continue;
1241 if (*src == '\n')
1243 *dst++ = ' ';
1245 else
1247 last_nonnl = dst;
1248 *dst++ = *src;
1251 *(++last_nonnl) = '\0';
1252 *length = last_nonnl - buffer;
1257 int shell_function_pid = 0, shell_function_completed;
1260 #ifdef WINDOWS32
1261 /*untested*/
1263 #include <windows.h>
1264 #include <io.h>
1265 #include "sub_proc.h"
1268 void
1269 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1271 SECURITY_ATTRIBUTES saAttr;
1272 HANDLE hIn;
1273 HANDLE hErr;
1274 HANDLE hChildOutRd;
1275 HANDLE hChildOutWr;
1276 HANDLE hProcess;
1279 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1280 saAttr.bInheritHandle = TRUE;
1281 saAttr.lpSecurityDescriptor = NULL;
1283 if (DuplicateHandle (GetCurrentProcess(),
1284 GetStdHandle(STD_INPUT_HANDLE),
1285 GetCurrentProcess(),
1286 &hIn,
1288 TRUE,
1289 DUPLICATE_SAME_ACCESS) == FALSE) {
1290 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1291 GetLastError());
1294 if (DuplicateHandle(GetCurrentProcess(),
1295 GetStdHandle(STD_ERROR_HANDLE),
1296 GetCurrentProcess(),
1297 &hErr,
1299 TRUE,
1300 DUPLICATE_SAME_ACCESS) == FALSE) {
1301 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1302 GetLastError());
1305 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1306 fatal (NILF, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1308 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1310 if (!hProcess)
1311 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1313 /* make sure that CreateProcess() has Path it needs */
1314 sync_Path_environment();
1316 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1317 /* register process for wait */
1318 process_register(hProcess);
1320 /* set the pid for returning to caller */
1321 *pid_p = (int) hProcess;
1323 /* set up to read data from child */
1324 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1326 /* this will be closed almost right away */
1327 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1328 } else {
1329 /* reap/cleanup the failed process */
1330 process_cleanup(hProcess);
1332 /* close handles which were duplicated, they weren't used */
1333 CloseHandle(hIn);
1334 CloseHandle(hErr);
1336 /* close pipe handles, they won't be used */
1337 CloseHandle(hChildOutRd);
1338 CloseHandle(hChildOutWr);
1340 /* set status for return */
1341 pipedes[0] = pipedes[1] = -1;
1342 *pid_p = -1;
1345 #endif
1348 #ifdef __MSDOS__
1349 FILE *
1350 msdos_openpipe (int* pipedes, int *pidp, char *text)
1352 FILE *fpipe=0;
1353 /* MSDOS can't fork, but it has `popen'. */
1354 struct variable *sh = lookup_variable ("SHELL", 5);
1355 int e;
1356 extern int dos_command_running, dos_status;
1358 /* Make sure not to bother processing an empty line. */
1359 while (isblank ((unsigned char)*text))
1360 ++text;
1361 if (*text == '\0')
1362 return 0;
1364 if (sh)
1366 char buf[PATH_MAX + 7];
1367 /* This makes sure $SHELL value is used by $(shell), even
1368 though the target environment is not passed to it. */
1369 sprintf (buf, "SHELL=%s", sh->value);
1370 putenv (buf);
1373 e = errno;
1374 errno = 0;
1375 dos_command_running = 1;
1376 dos_status = 0;
1377 /* If dos_status becomes non-zero, it means the child process
1378 was interrupted by a signal, like SIGINT or SIGQUIT. See
1379 fatal_error_signal in commands.c. */
1380 fpipe = popen (text, "rt");
1381 dos_command_running = 0;
1382 if (!fpipe || dos_status)
1384 pipedes[0] = -1;
1385 *pidp = -1;
1386 if (dos_status)
1387 errno = EINTR;
1388 else if (errno == 0)
1389 errno = ENOMEM;
1390 shell_function_completed = -1;
1392 else
1394 pipedes[0] = fileno (fpipe);
1395 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1396 errno = e;
1397 shell_function_completed = 1;
1399 return fpipe;
1401 #endif
1404 Do shell spawning, with the naughty bits for different OSes.
1407 #ifdef VMS
1409 /* VMS can't do $(shell ...) */
1410 #define func_shell 0
1412 #else
1413 #ifndef _AMIGA
1414 static char *
1415 func_shell (char *o, char **argv, const char *funcname)
1417 char* batch_filename = NULL;
1418 int i;
1420 #ifdef __MSDOS__
1421 FILE *fpipe;
1422 #endif
1423 char **command_argv;
1424 char *error_prefix;
1425 char **envp;
1426 int pipedes[2];
1427 int pid;
1429 #ifndef __MSDOS__
1430 /* Construct the argument list. */
1431 command_argv = construct_command_argv (argv[0],
1432 (char **) NULL, (struct file *) 0,
1433 &batch_filename);
1434 if (command_argv == 0)
1435 return o;
1436 #endif
1438 /* Using a target environment for `shell' loses in cases like:
1439 export var = $(shell echo foobie)
1440 because target_environment hits a loop trying to expand $(var)
1441 to put it in the environment. This is even more confusing when
1442 var was not explicitly exported, but just appeared in the
1443 calling environment. */
1445 envp = environ;
1447 /* For error messages. */
1448 if (reading_file != 0)
1450 error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1451 sprintf (error_prefix,
1452 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1454 else
1455 error_prefix = "";
1457 #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
1468 #elif defined(__MSDOS__)
1470 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1471 if (pipedes[0] < 0)
1473 perror_with_name (error_prefix, "pipe");
1474 return o;
1477 #else
1479 if (pipe (pipedes) < 0)
1481 perror_with_name (error_prefix, "pipe");
1482 return o;
1485 # ifdef __EMX__
1487 /* close some handles that are unnecessary for the child process */
1488 CLOSE_ON_EXEC(pipedes[1]);
1489 CLOSE_ON_EXEC(pipedes[0]);
1490 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1491 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1492 if (pid < 0)
1493 perror_with_name (error_prefix, "spawn");
1495 # else /* ! __EMX__ */
1497 pid = vfork ();
1498 if (pid < 0)
1499 perror_with_name (error_prefix, "fork");
1500 else if (pid == 0)
1501 child_execute_job (0, pipedes[1], command_argv, envp);
1502 else
1504 # endif
1506 #endif
1508 /* We are the parent. */
1510 char *buffer;
1511 unsigned int maxlen;
1512 int cc;
1514 /* Record the PID for reap_children. */
1515 shell_function_pid = pid;
1516 #ifndef __MSDOS__
1517 shell_function_completed = 0;
1519 /* Free the storage only the child needed. */
1520 free (command_argv[0]);
1521 free ((char *) command_argv);
1523 /* Close the write side of the pipe. */
1524 (void) close (pipedes[1]);
1525 #endif
1527 /* Set up and read from the pipe. */
1529 maxlen = 200;
1530 buffer = (char *) xmalloc (maxlen + 1);
1532 /* Read from the pipe until it gets EOF. */
1533 for (i = 0; ; i += cc)
1535 if (i == maxlen)
1537 maxlen += 512;
1538 buffer = (char *) xrealloc (buffer, maxlen + 1);
1541 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1542 if (cc <= 0)
1543 break;
1545 buffer[i] = '\0';
1547 /* Close the read side of the pipe. */
1548 #ifdef __MSDOS__
1549 if (fpipe)
1550 (void) pclose (fpipe);
1551 #else
1552 (void) close (pipedes[0]);
1553 #endif
1555 /* Loop until child_handler or reap_children() sets
1556 shell_function_completed to the status of our child shell. */
1557 while (shell_function_completed == 0)
1558 reap_children (1, 0);
1560 if (batch_filename) {
1561 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1562 batch_filename));
1563 remove (batch_filename);
1564 free (batch_filename);
1566 shell_function_pid = 0;
1568 /* The child_handler function will set shell_function_completed
1569 to 1 when the child dies normally, or to -1 if it
1570 dies with status 127, which is most likely an exec fail. */
1572 if (shell_function_completed == -1)
1574 /* This most likely means that the execvp failed,
1575 so we should just write out the error message
1576 that came in over the pipe from the child. */
1577 fputs (buffer, stderr);
1578 fflush (stderr);
1580 else
1582 /* The child finished normally. Replace all
1583 newlines in its output with spaces, and put
1584 that in the variable output buffer. */
1585 fold_newlines (buffer, &i);
1586 o = variable_buffer_output (o, buffer, i);
1589 free (buffer);
1592 return o;
1595 #else /* _AMIGA */
1597 /* Do the Amiga version of func_shell. */
1599 static char *
1600 func_shell (char *o, char **argv, const char *funcname)
1602 /* Amiga can't fork nor spawn, but I can start a program with
1603 redirection of my choice. However, this means that we
1604 don't have an opportunity to reopen stdout to trap it. Thus,
1605 we save our own stdout onto a new descriptor and dup a temp
1606 file's descriptor onto our stdout temporarily. After we
1607 spawn the shell program, we dup our own stdout back to the
1608 stdout descriptor. The buffer reading is the same as above,
1609 except that we're now reading from a file. */
1611 #include <dos/dos.h>
1612 #include <proto/dos.h>
1614 BPTR child_stdout;
1615 char tmp_output[FILENAME_MAX];
1616 unsigned int maxlen = 200;
1617 int cc, i;
1618 char * buffer, * ptr;
1619 char ** aptr;
1620 int len = 0;
1621 char* batch_filename = NULL;
1623 /* Construct the argument list. */
1624 command_argv = construct_command_argv (argv[0], (char **) NULL,
1625 (struct file *) 0, &batch_filename);
1626 if (command_argv == 0)
1627 return o;
1629 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1630 Ideally we would use main.c:open_tmpfile(), but this uses a special
1631 Open(), not fopen(), and I'm not familiar enough with the code to mess
1632 with it. */
1633 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1634 mktemp (tmp_output);
1635 child_stdout = Open (tmp_output, MODE_NEWFILE);
1637 for (aptr=command_argv; *aptr; aptr++)
1638 len += strlen (*aptr) + 1;
1640 buffer = xmalloc (len + 1);
1641 ptr = buffer;
1643 for (aptr=command_argv; *aptr; aptr++)
1645 strcpy (ptr, *aptr);
1646 ptr += strlen (ptr) + 1;
1647 *ptr ++ = ' ';
1648 *ptr = 0;
1651 ptr[-1] = '\n';
1653 Execute (buffer, NULL, child_stdout);
1654 free (buffer);
1656 Close (child_stdout);
1658 child_stdout = Open (tmp_output, MODE_OLDFILE);
1660 buffer = xmalloc (maxlen);
1661 i = 0;
1664 if (i == maxlen)
1666 maxlen += 512;
1667 buffer = (char *) xrealloc (buffer, maxlen + 1);
1670 cc = Read (child_stdout, &buffer[i], maxlen - i);
1671 if (cc > 0)
1672 i += cc;
1673 } while (cc > 0);
1675 Close (child_stdout);
1677 fold_newlines (buffer, &i);
1678 o = variable_buffer_output (o, buffer, i);
1679 free (buffer);
1680 return o;
1682 #endif /* _AMIGA */
1683 #endif /* !VMS */
1685 #ifdef EXPERIMENTAL
1688 equality. Return is string-boolean, ie, the empty string is false.
1690 static char *
1691 func_eq (char* o, char **argv, char *funcname)
1693 int result = ! strcmp (argv[0], argv[1]);
1694 o = variable_buffer_output (o, result ? "1" : "", result);
1695 return o;
1700 string-boolean not operator.
1702 static char *
1703 func_not (char* o, char **argv, char *funcname)
1705 char * s = argv[0];
1706 int result = 0;
1707 while (isspace ((unsigned char)*s))
1708 s++;
1709 result = ! (*s);
1710 o = variable_buffer_output (o, result ? "1" : "", result);
1711 return o;
1713 #endif
1716 /* Lookup table for builtin functions.
1718 This doesn't have to be sorted; we use a straight lookup. We might gain
1719 some efficiency by moving most often used functions to the start of the
1720 table.
1722 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1723 comma-separated values are treated as arguments.
1725 EXPAND_ARGS means that all arguments should be expanded before invocation.
1726 Functions that do namespace tricks (foreach) don't automatically expand. */
1728 static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
1731 static struct function_table_entry function_table_init[] =
1733 /* Name/size */ /* MIN MAX EXP? Function */
1734 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
1735 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
1736 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
1737 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
1738 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
1739 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
1740 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
1741 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
1742 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
1743 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
1744 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
1745 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
1746 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
1747 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
1748 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
1749 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
1750 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
1751 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
1752 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
1753 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
1754 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
1755 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
1756 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
1757 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
1758 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
1759 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
1760 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
1761 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
1762 #ifdef EXPERIMENTAL
1763 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
1764 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
1765 #endif
1768 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1771 /* These must come after the definition of function_table. */
1773 static char *
1774 expand_builtin_function (char *o, int argc, char **argv,
1775 const struct function_table_entry *entry_p)
1777 if (argc < (int)entry_p->minimum_args)
1778 fatal (reading_file,
1779 _("Insufficient number of arguments (%d) to function `%s'"),
1780 argc, entry_p->name);
1782 /* I suppose technically some function could do something with no
1783 arguments, but so far none do, so just test it for all functions here
1784 rather than in each one. We can change it later if necessary. */
1786 if (!argc)
1787 return o;
1789 if (!entry_p->func_ptr)
1790 fatal (reading_file, _("Unimplemented on this platform: function `%s'"),
1791 entry_p->name);
1793 return entry_p->func_ptr (o, argv, entry_p->name);
1796 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1797 opening ( or { and is not null-terminated. If a function invocation
1798 is found, expand it into the buffer at *OP, updating *OP, incrementing
1799 *STRINGP past the reference and returning nonzero. If not, return zero. */
1802 handle_function (char **op, char **stringp)
1804 const struct function_table_entry *entry_p;
1805 char openparen = (*stringp)[0];
1806 char closeparen = openparen == '(' ? ')' : '}';
1807 char *beg;
1808 char *end;
1809 int count = 0;
1810 register char *p;
1811 char **argv, **argvp;
1812 int nargs;
1814 beg = *stringp + 1;
1816 entry_p = lookup_function (beg);
1818 if (!entry_p)
1819 return 0;
1821 /* We found a builtin function. Find the beginning of its arguments (skip
1822 whitespace after the name). */
1824 beg = next_token (beg + entry_p->len);
1826 /* Find the end of the function invocation, counting nested use of
1827 whichever kind of parens we use. Since we're looking, count commas
1828 to get a rough estimate of how many arguments we might have. The
1829 count might be high, but it'll never be low. */
1831 for (nargs=1, end=beg; *end != '\0'; ++end)
1832 if (*end == ',')
1833 ++nargs;
1834 else if (*end == openparen)
1835 ++count;
1836 else if (*end == closeparen && --count < 0)
1837 break;
1839 if (count >= 0)
1840 fatal (reading_file,
1841 _("unterminated call to function `%s': missing `%c'"),
1842 entry_p->name, closeparen);
1844 *stringp = end;
1846 /* Get some memory to store the arg pointers. */
1847 argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
1849 /* Chop the string into arguments, then a nul. As soon as we hit
1850 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1851 last argument.
1853 If we're expanding, store pointers to the expansion of each one. If
1854 not, make a duplicate of the string and point into that, nul-terminating
1855 each argument. */
1857 if (!entry_p->expand_args)
1859 int len = end - beg;
1861 p = xmalloc (len+1);
1862 memcpy (p, beg, len);
1863 p[len] = '\0';
1864 beg = p;
1865 end = beg + len;
1868 for (p=beg, nargs=0; p <= end; ++argvp)
1870 char *next;
1872 ++nargs;
1874 if (nargs == entry_p->maximum_args
1875 || (! (next = find_next_argument (openparen, closeparen, p, end))))
1876 next = end;
1878 if (entry_p->expand_args)
1879 *argvp = expand_argument (p, next);
1880 else
1882 *argvp = p;
1883 *next = '\0';
1886 p = next + 1;
1888 *argvp = NULL;
1890 /* Finally! Run the function... */
1891 *op = expand_builtin_function (*op, nargs, argv, entry_p);
1893 /* Free memory. */
1894 if (entry_p->expand_args)
1895 for (argvp=argv; *argvp != 0; ++argvp)
1896 free (*argvp);
1897 else
1898 free (beg);
1900 return 1;
1904 /* User-defined functions. Expand the first argument as either a builtin
1905 function or a make variable, in the context of the rest of the arguments
1906 assigned to $1, $2, ... $N. $0 is the name of the function. */
1908 static char *
1909 func_call (char *o, char **argv, const char *funcname)
1911 static int max_args = 0;
1912 char *fname;
1913 char *cp;
1914 char *body;
1915 int flen;
1916 int i;
1917 int saved_args;
1918 const struct function_table_entry *entry_p;
1919 struct variable *v;
1921 /* There is no way to define a variable with a space in the name, so strip
1922 leading and trailing whitespace as a favor to the user. */
1923 fname = argv[0];
1924 while (*fname != '\0' && isspace ((unsigned char)*fname))
1925 ++fname;
1927 cp = fname + strlen (fname) - 1;
1928 while (cp > fname && isspace ((unsigned char)*cp))
1929 --cp;
1930 cp[1] = '\0';
1932 /* Calling nothing is a no-op */
1933 if (*fname == '\0')
1934 return o;
1936 /* Are we invoking a builtin function? */
1938 entry_p = lookup_function (fname);
1940 if (entry_p)
1942 /* How many arguments do we have? */
1943 for (i=0; argv[i+1]; ++i)
1946 return expand_builtin_function (o, i, argv+1, entry_p);
1949 /* Not a builtin, so the first argument is the name of a variable to be
1950 expanded and interpreted as a function. Find it. */
1951 flen = strlen (fname);
1953 v = lookup_variable (fname, flen);
1955 if (v == 0)
1956 warn_undefined (fname, flen);
1958 if (v == 0 || *v->value == '\0')
1959 return o;
1961 body = (char *) alloca (flen + 4);
1962 body[0] = '$';
1963 body[1] = '(';
1964 memcpy (body + 2, fname, flen);
1965 body[flen+2] = ')';
1966 body[flen+3] = '\0';
1968 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
1970 push_new_variable_scope ();
1972 for (i=0; *argv; ++i, ++argv)
1974 char num[11];
1976 sprintf (num, "%d", i);
1977 define_variable (num, strlen (num), *argv, o_automatic, 0);
1980 /* If the number of arguments we have is < max_args, it means we're inside
1981 a recursive invocation of $(call ...). Fill in the remaining arguments
1982 in the new scope with the empty value, to hide them from this
1983 invocation. */
1985 for (; i < max_args; ++i)
1987 char num[11];
1989 sprintf (num, "%d", i);
1990 define_variable (num, strlen (num), "", o_automatic, 0);
1993 /* Expand the body in the context of the arguments, adding the result to
1994 the variable buffer. */
1996 v->exp_count = EXP_COUNT_MAX;
1998 saved_args = max_args;
1999 max_args = i;
2000 o = variable_expand_string (o, body, flen+3);
2001 max_args = saved_args;
2003 v->exp_count = 0;
2005 pop_variable_scope ();
2007 return o + strlen (o);
2010 void
2011 hash_init_function_table (void)
2013 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2014 function_table_entry_hash_1, function_table_entry_hash_2,
2015 function_table_entry_hash_cmp);
2016 hash_load (&function_table, function_table_init,
2017 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));