Sync usage with man page.
[netbsd-mini2440.git] / gnu / dist / gmake / function.c
blobcf646d6fba877dcfa366b833b7408555d1970791
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 (keyv)
45 const void *keyv;
47 struct function_table_entry const *key = (struct function_table_entry const *) keyv;
48 return_STRING_N_HASH_1 (key->name, key->len);
51 static unsigned long
52 function_table_entry_hash_2 (keyv)
53 const void *keyv;
55 struct function_table_entry const *key = (struct function_table_entry const *) keyv;
56 return_STRING_N_HASH_2 (key->name, key->len);
59 static int
60 function_table_entry_hash_cmp (xv, yv)
61 const void *xv;
62 const void *yv;
64 struct function_table_entry const *x = (struct function_table_entry const *) xv;
65 struct function_table_entry const *y = (struct function_table_entry const *) yv;
66 int result = x->len - y->len;
67 if (result)
68 return result;
69 return_STRING_N_COMPARE (x->name, y->name, x->len);
72 static struct hash_table function_table;
75 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
76 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
77 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
78 nonzero, substitutions are done only on matches which are complete
79 whitespace-delimited words. If SUFFIX_ONLY is nonzero, substitutions are
80 done only at the ends of whitespace-delimited words. */
82 char *
83 subst_expand (o, text, subst, replace, slen, rlen, by_word, suffix_only)
84 char *o;
85 char *text;
86 char *subst, *replace;
87 unsigned int slen, rlen;
88 int by_word, suffix_only;
90 register char *t = text;
91 register char *p;
93 if (slen == 0 && !by_word && !suffix_only)
95 /* The first occurrence of "" in any string is its end. */
96 o = variable_buffer_output (o, t, strlen (t));
97 if (rlen > 0)
98 o = variable_buffer_output (o, replace, rlen);
99 return o;
104 if ((by_word | suffix_only) && slen == 0)
105 /* When matching by words, the empty string should match
106 the end of each word, rather than the end of the whole text. */
107 p = end_of_token (next_token (t));
108 else
110 p = sindex (t, 0, subst, slen);
111 if (p == 0)
113 /* No more matches. Output everything left on the end. */
114 o = variable_buffer_output (o, t, strlen (t));
115 return o;
119 /* Output everything before this occurrence of the string to replace. */
120 if (p > t)
121 o = variable_buffer_output (o, t, p - t);
123 /* If we're substituting only by fully matched words,
124 or only at the ends of words, check that this case qualifies. */
125 if ((by_word
126 && ((p > t && !isblank ((unsigned char)p[-1]))
127 || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
128 || (suffix_only
129 && (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
130 /* Struck out. Output the rest of the string that is
131 no longer to be replaced. */
132 o = variable_buffer_output (o, subst, slen);
133 else if (rlen > 0)
134 /* Output the replacement string. */
135 o = variable_buffer_output (o, replace, rlen);
137 /* Advance T past the string to be replaced. */
138 t = p + slen;
139 } while (*t != '\0');
141 return o;
145 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
146 and replacing strings matching PATTERN with REPLACE.
147 If PATTERN_PERCENT is not nil, PATTERN has already been
148 run through find_percent, and PATTERN_PERCENT is the result.
149 If REPLACE_PERCENT is not nil, REPLACE has already been
150 run through find_percent, and REPLACE_PERCENT is the result. */
152 char *
153 patsubst_expand (o, text, pattern, replace, pattern_percent, replace_percent)
154 char *o;
155 char *text;
156 register char *pattern, *replace;
157 register char *pattern_percent, *replace_percent;
159 unsigned int pattern_prepercent_len, pattern_postpercent_len;
160 unsigned int replace_prepercent_len, replace_postpercent_len = 0;
161 char *t;
162 unsigned int len;
163 int doneany = 0;
165 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
166 will be collapsed before we call subst_expand if PATTERN has no %. */
167 if (replace_percent == 0)
168 replace_percent = find_percent (replace);
169 if (replace_percent != 0)
171 /* Record the length of REPLACE before and after the % so
172 we don't have to compute these lengths more than once. */
173 replace_prepercent_len = replace_percent - replace;
174 replace_postpercent_len = strlen (replace_percent + 1);
176 else
177 /* We store the length of the replacement
178 so we only need to compute it once. */
179 replace_prepercent_len = strlen (replace);
181 if (pattern_percent == 0)
182 pattern_percent = find_percent (pattern);
183 if (pattern_percent == 0)
184 /* With no % in the pattern, this is just a simple substitution. */
185 return subst_expand (o, text, pattern, replace,
186 strlen (pattern), strlen (replace), 1, 0);
188 /* Record the length of PATTERN before and after the %
189 so we don't have to compute it more than once. */
190 pattern_prepercent_len = pattern_percent - pattern;
191 pattern_postpercent_len = strlen (pattern_percent + 1);
193 while ((t = find_next_token (&text, &len)) != 0)
195 int fail = 0;
197 /* Is it big enough to match? */
198 if (len < pattern_prepercent_len + pattern_postpercent_len)
199 fail = 1;
201 /* Does the prefix match? */
202 if (!fail && pattern_prepercent_len > 0
203 && (*t != *pattern
204 || t[pattern_prepercent_len - 1] != pattern_percent[-1]
205 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
206 fail = 1;
208 /* Does the suffix match? */
209 if (!fail && pattern_postpercent_len > 0
210 && (t[len - 1] != pattern_percent[pattern_postpercent_len]
211 || t[len - pattern_postpercent_len] != pattern_percent[1]
212 || !strneq (&t[len - pattern_postpercent_len],
213 &pattern_percent[1], pattern_postpercent_len - 1)))
214 fail = 1;
216 if (fail)
217 /* It didn't match. Output the string. */
218 o = variable_buffer_output (o, t, len);
219 else
221 /* It matched. Output the replacement. */
223 /* Output the part of the replacement before the %. */
224 o = variable_buffer_output (o, replace, replace_prepercent_len);
226 if (replace_percent != 0)
228 /* Output the part of the matched string that
229 matched the % in the pattern. */
230 o = variable_buffer_output (o, t + pattern_prepercent_len,
231 len - (pattern_prepercent_len
232 + pattern_postpercent_len));
233 /* Output the part of the replacement after the %. */
234 o = variable_buffer_output (o, replace_percent + 1,
235 replace_postpercent_len);
239 /* Output a space, but not if the replacement is "". */
240 if (fail || replace_prepercent_len > 0
241 || (replace_percent != 0 && len + replace_postpercent_len > 0))
243 o = variable_buffer_output (o, " ", 1);
244 doneany = 1;
247 if (doneany)
248 /* Kill the last space. */
249 --o;
251 return o;
255 /* Look up a function by name. */
257 static const struct function_table_entry *
258 lookup_function (s)
259 const char *s;
261 const char *e = s;
263 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
264 e++;
265 if (*e == '\0' || isblank ((unsigned char) *e))
267 struct function_table_entry function_table_entry_key;
268 function_table_entry_key.name = s;
269 function_table_entry_key.len = e - s;
271 return hash_find_item (&function_table, &function_table_entry_key);
273 return 0;
277 /* Return 1 if PATTERN matches STR, 0 if not. */
280 pattern_matches (pattern, percent, str)
281 register char *pattern, *percent, *str;
283 unsigned int sfxlen, strlength;
285 if (percent == 0)
287 unsigned int len = strlen (pattern) + 1;
288 char *new_chars = (char *) alloca (len);
289 bcopy (pattern, new_chars, len);
290 pattern = new_chars;
291 percent = find_percent (pattern);
292 if (percent == 0)
293 return streq (pattern, str);
296 sfxlen = strlen (percent + 1);
297 strlength = strlen (str);
299 if (strlength < (percent - pattern) + sfxlen
300 || !strneq (pattern, str, percent - pattern))
301 return 0;
303 return !strcmp (percent + 1, str + (strlength - sfxlen));
307 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
308 ENDPARENtheses), starting at PTR before END. Return a pointer to
309 next character.
311 If no next argument is found, return NULL.
314 static char *
315 find_next_argument (startparen, endparen, ptr, end)
316 char startparen;
317 char endparen;
318 const char *ptr;
319 const char *end;
321 int count = 0;
323 for (; ptr < end; ++ptr)
324 if (*ptr == startparen)
325 ++count;
327 else if (*ptr == endparen)
329 --count;
330 if (count < 0)
331 return NULL;
334 else if (*ptr == ',' && !count)
335 return (char *)ptr;
337 /* We didn't find anything. */
338 return NULL;
342 /* Glob-expand LINE. The returned pointer is
343 only good until the next call to string_glob. */
345 static char *
346 string_glob (line)
347 char *line;
349 static char *result = 0;
350 static unsigned int length;
351 register struct nameseq *chain;
352 register unsigned int idx;
354 chain = multi_glob (parse_file_seq
355 (&line, '\0', sizeof (struct nameseq),
356 /* We do not want parse_file_seq to strip `./'s.
357 That would break examples like:
358 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
360 sizeof (struct nameseq));
362 if (result == 0)
364 length = 100;
365 result = (char *) xmalloc (100);
368 idx = 0;
369 while (chain != 0)
371 register char *name = chain->name;
372 unsigned int len = strlen (name);
374 struct nameseq *next = chain->next;
375 free ((char *) chain);
376 chain = next;
378 /* multi_glob will pass names without globbing metacharacters
379 through as is, but we want only files that actually exist. */
380 if (file_exists_p (name))
382 if (idx + len + 1 > length)
384 length += (len + 1) * 2;
385 result = (char *) xrealloc (result, length);
387 bcopy (name, &result[idx], len);
388 idx += len;
389 result[idx++] = ' ';
392 free (name);
395 /* Kill the last space and terminate the string. */
396 if (idx == 0)
397 result[0] = '\0';
398 else
399 result[idx - 1] = '\0';
401 return result;
405 Builtin functions
408 static char *
409 func_patsubst (o, argv, funcname)
410 char *o;
411 char **argv;
412 const char *funcname;
414 o = patsubst_expand (o, argv[2], argv[0], argv[1], (char *) 0, (char *) 0);
415 return o;
419 static char *
420 func_join (o, argv, funcname)
421 char *o;
422 char **argv;
423 const char *funcname;
425 int doneany = 0;
427 /* Write each word of the first argument directly followed
428 by the corresponding word of the second argument.
429 If the two arguments have a different number of words,
430 the excess words are just output separated by blanks. */
431 register char *tp;
432 register char *pp;
433 char *list1_iterator = argv[0];
434 char *list2_iterator = argv[1];
437 unsigned int len1, len2;
439 tp = find_next_token (&list1_iterator, &len1);
440 if (tp != 0)
441 o = variable_buffer_output (o, tp, len1);
443 pp = find_next_token (&list2_iterator, &len2);
444 if (pp != 0)
445 o = variable_buffer_output (o, pp, len2);
447 if (tp != 0 || pp != 0)
449 o = variable_buffer_output (o, " ", 1);
450 doneany = 1;
453 while (tp != 0 || pp != 0);
454 if (doneany)
455 /* Kill the last blank. */
456 --o;
458 return o;
462 static char *
463 func_origin (o, argv, funcname)
464 char *o;
465 char **argv;
466 const char *funcname;
468 /* Expand the argument. */
469 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
470 if (v == 0)
471 o = variable_buffer_output (o, "undefined", 9);
472 else
473 switch (v->origin)
475 default:
476 case o_invalid:
477 abort ();
478 break;
479 case o_default:
480 o = variable_buffer_output (o, "default", 7);
481 break;
482 case o_env:
483 o = variable_buffer_output (o, "environment", 11);
484 break;
485 case o_file:
486 o = variable_buffer_output (o, "file", 4);
487 break;
488 case o_env_override:
489 o = variable_buffer_output (o, "environment override", 20);
490 break;
491 case o_command:
492 o = variable_buffer_output (o, "command line", 12);
493 break;
494 case o_override:
495 o = variable_buffer_output (o, "override", 8);
496 break;
497 case o_automatic:
498 o = variable_buffer_output (o, "automatic", 9);
499 break;
502 return o;
505 #ifdef VMS
506 # define IS_PATHSEP(c) ((c) == ']')
507 #else
508 # ifdef HAVE_DOS_PATHS
509 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
510 # else
511 # define IS_PATHSEP(c) ((c) == '/')
512 # endif
513 #endif
516 static char *
517 func_notdir_suffix (o, argv, funcname)
518 char *o;
519 char **argv;
520 const char *funcname;
522 /* Expand the argument. */
523 char *list_iterator = argv[0];
524 char *p2 =0;
525 int doneany =0;
526 unsigned int len=0;
528 int is_suffix = streq (funcname, "suffix");
529 int is_notdir = !is_suffix;
530 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
532 char *p = p2 + len;
535 while (p >= p2 && (!is_suffix || *p != '.'))
537 if (IS_PATHSEP (*p))
538 break;
539 --p;
542 if (p >= p2)
544 if (is_notdir)
545 ++p;
546 else if (*p != '.')
547 continue;
548 o = variable_buffer_output (o, p, len - (p - p2));
550 #ifdef HAVE_DOS_PATHS
551 /* Handle the case of "d:foo/bar". */
552 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
554 p = p2 + 2;
555 o = variable_buffer_output (o, p, len - (p - p2));
557 #endif
558 else if (is_notdir)
559 o = variable_buffer_output (o, p2, len);
561 if (is_notdir || p >= p2)
563 o = variable_buffer_output (o, " ", 1);
564 doneany = 1;
567 if (doneany)
568 /* Kill last space. */
569 --o;
572 return o;
577 static char *
578 func_basename_dir (o, argv, funcname)
579 char *o;
580 char **argv;
581 const char *funcname;
583 /* Expand the argument. */
584 char *p3 = argv[0];
585 char *p2=0;
586 int doneany=0;
587 unsigned int len=0;
588 char *p=0;
589 int is_basename= streq (funcname, "basename");
590 int is_dir= !is_basename;
592 while ((p2 = find_next_token (&p3, &len)) != 0)
594 p = p2 + len;
595 while (p >= p2 && (!is_basename || *p != '.'))
597 if (IS_PATHSEP (*p))
598 break;
599 --p;
602 if (p >= p2 && (is_dir))
603 o = variable_buffer_output (o, p2, ++p - p2);
604 else if (p >= p2 && (*p == '.'))
605 o = variable_buffer_output (o, p2, p - p2);
606 #ifdef HAVE_DOS_PATHS
607 /* Handle the "d:foobar" case */
608 else if (p2[0] && p2[1] == ':' && is_dir)
609 o = variable_buffer_output (o, p2, 2);
610 #endif
611 else if (is_dir)
612 #ifdef VMS
613 o = variable_buffer_output (o, "[]", 2);
614 #else
615 #ifndef _AMIGA
616 o = variable_buffer_output (o, "./", 2);
617 #else
618 ; /* Just a nop... */
619 #endif /* AMIGA */
620 #endif /* !VMS */
621 else
622 /* The entire name is the basename. */
623 o = variable_buffer_output (o, p2, len);
625 o = variable_buffer_output (o, " ", 1);
626 doneany = 1;
628 if (doneany)
629 /* Kill last space. */
630 --o;
633 return o;
636 static char *
637 func_addsuffix_addprefix (o, argv, funcname)
638 char *o;
639 char **argv;
640 const char *funcname;
642 int fixlen = strlen (argv[0]);
643 char *list_iterator = argv[1];
644 int is_addprefix = streq (funcname, "addprefix");
645 int is_addsuffix = !is_addprefix;
647 int doneany = 0;
648 char *p;
649 unsigned int len;
651 while ((p = find_next_token (&list_iterator, &len)) != 0)
653 if (is_addprefix)
654 o = variable_buffer_output (o, argv[0], fixlen);
655 o = variable_buffer_output (o, p, len);
656 if (is_addsuffix)
657 o = variable_buffer_output (o, argv[0], fixlen);
658 o = variable_buffer_output (o, " ", 1);
659 doneany = 1;
662 if (doneany)
663 /* Kill last space. */
664 --o;
666 return o;
669 static char *
670 func_subst (o, argv, funcname)
671 char *o;
672 char **argv;
673 const char *funcname;
675 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
676 strlen (argv[1]), 0, 0);
678 return o;
682 static char *
683 func_firstword (o, argv, funcname)
684 char *o;
685 char **argv;
686 const char *funcname;
688 unsigned int i;
689 char *words = argv[0]; /* Use a temp variable for find_next_token */
690 char *p = find_next_token (&words, &i);
692 if (p != 0)
693 o = variable_buffer_output (o, p, i);
695 return o;
699 static char *
700 func_words (o, argv, funcname)
701 char *o;
702 char **argv;
703 const char *funcname;
705 int i = 0;
706 char *word_iterator = argv[0];
707 char buf[20];
709 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
710 ++i;
712 sprintf (buf, "%d", i);
713 o = variable_buffer_output (o, buf, strlen (buf));
716 return o;
719 char *
720 strip_whitespace (begpp, endpp)
721 char **begpp;
722 char **endpp;
724 while (isspace ((unsigned char)**begpp) && *begpp <= *endpp)
725 (*begpp) ++;
726 while (isspace ((unsigned char)**endpp) && *endpp >= *begpp)
727 (*endpp) --;
728 return *begpp;
732 is_numeric (p)
733 char *p;
735 char *end = p + strlen (p) - 1;
736 char *beg = p;
737 strip_whitespace (&p, &end);
739 while (p <= end)
740 if (!ISDIGIT (*(p++))) /* ISDIGIT only evals its arg once: see make.h. */
741 return 0;
743 return (end - beg >= 0);
746 void
747 check_numeric (s, message)
748 char *s;
749 char *message;
751 if (!is_numeric (s))
752 fatal (reading_file, message);
757 static char *
758 func_word (o, argv, funcname)
759 char *o;
760 char **argv;
761 const char *funcname;
763 char *end_p=0;
764 int i=0;
765 char *p=0;
767 /* Check the first argument. */
768 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
769 i = atoi (argv[0]);
771 if (i == 0)
772 fatal (reading_file, _("first argument to `word' function must be greater than 0"));
775 end_p = argv[1];
776 while ((p = find_next_token (&end_p, 0)) != 0)
777 if (--i == 0)
778 break;
780 if (i == 0)
781 o = variable_buffer_output (o, p, end_p - p);
783 return o;
786 static char *
787 func_wordlist (o, argv, funcname)
788 char *o;
789 char **argv;
790 const char *funcname;
792 int start, count;
794 /* Check the arguments. */
795 check_numeric (argv[0],
796 _("non-numeric first argument to `wordlist' function"));
797 check_numeric (argv[1],
798 _("non-numeric second argument to `wordlist' function"));
800 start = atoi (argv[0]);
801 count = atoi (argv[1]) - start + 1;
803 if (count > 0)
805 char *p;
806 char *end_p = argv[2];
808 /* Find the beginning of the "start"th word. */
809 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
812 if (p)
814 /* Find the end of the "count"th word from start. */
815 while (--count && (find_next_token (&end_p, 0) != 0))
818 /* Return the stuff in the middle. */
819 o = variable_buffer_output (o, p, end_p - p);
823 return o;
826 static char*
827 func_findstring (o, argv, funcname)
828 char *o;
829 char **argv;
830 const char *funcname;
832 /* Find the first occurrence of the first string in the second. */
833 int i = strlen (argv[0]);
834 if (sindex (argv[1], 0, argv[0], i) != 0)
835 o = variable_buffer_output (o, argv[0], i);
837 return o;
840 static char *
841 func_foreach (o, argv, funcname)
842 char *o;
843 char **argv;
844 const char *funcname;
846 /* expand only the first two. */
847 char *varname = expand_argument (argv[0], NULL);
848 char *list = expand_argument (argv[1], NULL);
849 char *body = argv[2];
851 int doneany = 0;
852 char *list_iterator = list;
853 char *p;
854 unsigned int len;
855 register struct variable *var;
857 push_new_variable_scope ();
858 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
860 /* loop through LIST, put the value in VAR and expand BODY */
861 while ((p = find_next_token (&list_iterator, &len)) != 0)
863 char *result = 0;
866 char save = p[len];
868 p[len] = '\0';
869 free (var->value);
870 var->value = (char *) xstrdup ((char*) p);
871 p[len] = save;
874 result = allocated_variable_expand (body);
876 o = variable_buffer_output (o, result, strlen (result));
877 o = variable_buffer_output (o, " ", 1);
878 doneany = 1;
879 free (result);
882 if (doneany)
883 /* Kill the last space. */
884 --o;
886 pop_variable_scope ();
887 free (varname);
888 free (list);
890 return o;
893 struct a_word
895 struct a_word *next;
896 struct a_word *chain;
897 char *str;
898 int length;
899 int matched;
902 static unsigned long
903 a_word_hash_1 (key)
904 const void *key;
906 return_STRING_HASH_1 (((struct a_word const *) key)->str);
909 static unsigned long
910 a_word_hash_2 (key)
911 const void *key;
913 return_STRING_HASH_2 (((struct a_word const *) key)->str);
916 static int
917 a_word_hash_cmp (x, y)
918 const void *x;
919 const void *y;
921 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
922 if (result)
923 return result;
924 return_STRING_COMPARE (((struct a_word const *) x)->str,
925 ((struct a_word const *) y)->str);
928 struct a_pattern
930 struct a_pattern *next;
931 char *str;
932 char *percent;
933 int length;
934 int save_c;
937 static char *
938 func_filter_filterout (o, argv, funcname)
939 char *o;
940 char **argv;
941 const char *funcname;
943 struct a_word *wordhead;
944 struct a_word **wordtail;
945 struct a_word *wp;
946 struct a_pattern *pathead;
947 struct a_pattern **pattail;
948 struct a_pattern *pp;
950 struct hash_table a_word_table;
951 int is_filter = streq (funcname, "filter");
952 char *pat_iterator = argv[0];
953 char *word_iterator = argv[1];
954 int literals = 0;
955 int words = 0;
956 int hashing = 0;
957 char *p;
958 unsigned int len;
960 /* Chop ARGV[0] up into patterns to match against the words. */
962 pattail = &pathead;
963 while ((p = find_next_token (&pat_iterator, &len)) != 0)
965 struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
967 *pattail = pat;
968 pattail = &pat->next;
970 if (*pat_iterator != '\0')
971 ++pat_iterator;
973 pat->str = p;
974 pat->length = len;
975 pat->save_c = p[len];
976 p[len] = '\0';
977 pat->percent = find_percent (p);
978 if (pat->percent == 0)
979 literals++;
981 *pattail = 0;
983 /* Chop ARGV[1] up into words to match against the patterns. */
985 wordtail = &wordhead;
986 while ((p = find_next_token (&word_iterator, &len)) != 0)
988 struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
990 *wordtail = word;
991 wordtail = &word->next;
993 if (*word_iterator != '\0')
994 ++word_iterator;
996 p[len] = '\0';
997 word->str = p;
998 word->length = len;
999 word->matched = 0;
1000 word->chain = 0;
1001 words++;
1003 *wordtail = 0;
1005 /* Only use a hash table if arg list lengths justifies the cost. */
1006 hashing = (literals >= 2 && (literals * words) >= 10);
1007 if (hashing)
1009 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
1010 for (wp = wordhead; wp != 0; wp = wp->next)
1012 struct a_word *owp = hash_insert (&a_word_table, wp);
1013 if (owp)
1014 wp->chain = owp;
1018 if (words)
1020 int doneany = 0;
1022 /* Run each pattern through the words, killing words. */
1023 for (pp = pathead; pp != 0; pp = pp->next)
1025 if (pp->percent)
1026 for (wp = wordhead; wp != 0; wp = wp->next)
1027 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1028 else if (hashing)
1030 struct a_word a_word_key;
1031 a_word_key.str = pp->str;
1032 a_word_key.length = pp->length;
1033 wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
1034 while (wp)
1036 wp->matched |= 1;
1037 wp = wp->chain;
1040 else
1041 for (wp = wordhead; wp != 0; wp = wp->next)
1042 wp->matched |= (wp->length == pp->length
1043 && strneq (pp->str, wp->str, wp->length));
1046 /* Output the words that matched (or didn't, for filter-out). */
1047 for (wp = wordhead; wp != 0; wp = wp->next)
1048 if (is_filter ? wp->matched : !wp->matched)
1050 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1051 o = variable_buffer_output (o, " ", 1);
1052 doneany = 1;
1055 if (doneany)
1056 /* Kill the last space. */
1057 --o;
1060 for (pp = pathead; pp != 0; pp = pp->next)
1061 pp->str[pp->length] = pp->save_c;
1063 if (hashing)
1064 hash_free (&a_word_table, 0);
1066 return o;
1070 static char *
1071 func_strip (o, argv, funcname)
1072 char *o;
1073 char **argv;
1074 const char *funcname;
1076 char *p = argv[0];
1077 int doneany =0;
1079 while (*p != '\0')
1081 int i=0;
1082 char *word_start=0;
1084 while (isspace ((unsigned char)*p))
1085 ++p;
1086 word_start = p;
1087 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1089 if (!i)
1090 break;
1091 o = variable_buffer_output (o, word_start, i);
1092 o = variable_buffer_output (o, " ", 1);
1093 doneany = 1;
1096 if (doneany)
1097 /* Kill the last space. */
1098 --o;
1099 return o;
1103 Print a warning or fatal message.
1105 static char *
1106 func_error (o, argv, funcname)
1107 char *o;
1108 char **argv;
1109 const char *funcname;
1111 char **argvp;
1112 char *msg, *p;
1113 int len;
1115 /* The arguments will be broken on commas. Rather than create yet
1116 another special case where function arguments aren't broken up,
1117 just create a format string that puts them back together. */
1118 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1119 len += strlen (*argvp) + 2;
1121 p = msg = (char *) alloca (len + 1);
1123 for (argvp=argv; argvp[1] != 0; ++argvp)
1125 strcpy (p, *argvp);
1126 p += strlen (*argvp);
1127 *(p++) = ',';
1128 *(p++) = ' ';
1130 strcpy (p, *argvp);
1132 if (*funcname == 'e')
1133 fatal (reading_file, "%s", msg);
1135 /* The warning function expands to the empty string. */
1136 error (reading_file, "%s", msg);
1138 return o;
1143 chop argv[0] into words, and sort them.
1145 static char *
1146 func_sort (o, argv, funcname)
1147 char *o;
1148 char **argv;
1149 const char *funcname;
1151 char **words = 0;
1152 int nwords = 0;
1153 register int wordi = 0;
1155 /* Chop ARGV[0] into words and put them in WORDS. */
1156 char *t = argv[0];
1157 char *p;
1158 unsigned int len;
1159 int i;
1161 while ((p = find_next_token (&t, &len)) != 0)
1163 if (wordi >= nwords - 1)
1165 nwords = (2 * nwords) + 5;
1166 words = (char **) xrealloc ((char *) words,
1167 nwords * sizeof (char *));
1169 words[wordi++] = savestring (p, len);
1172 if (!wordi)
1173 return o;
1175 /* Now sort the list of words. */
1176 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1178 /* Now write the sorted list. */
1179 for (i = 0; i < wordi; ++i)
1181 len = strlen (words[i]);
1182 if (i == wordi - 1 || strlen (words[i + 1]) != len
1183 || strcmp (words[i], words[i + 1]))
1185 o = variable_buffer_output (o, words[i], len);
1186 o = variable_buffer_output (o, " ", 1);
1188 free (words[i]);
1190 /* Kill the last space. */
1191 --o;
1193 free (words);
1195 return o;
1199 $(if condition,true-part[,false-part])
1201 CONDITION is false iff it evaluates to an empty string. White
1202 space before and after condition are stripped before evaluation.
1204 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1205 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1206 you can use $(if ...) to create side-effects (with $(shell ...), for
1207 example).
1210 static char *
1211 func_if (o, argv, funcname)
1212 char *o;
1213 char **argv;
1214 const char *funcname;
1216 char *begp = argv[0];
1217 char *endp = begp + strlen (argv[0]);
1218 int result = 0;
1220 /* Find the result of the condition: if we have a value, and it's not
1221 empty, the condition is true. If we don't have a value, or it's the
1222 empty string, then it's false. */
1224 strip_whitespace (&begp, &endp);
1226 if (begp < endp)
1228 char *expansion = expand_argument (begp, NULL);
1230 result = strlen (expansion);
1231 free (expansion);
1234 /* If the result is true (1) we want to eval the first argument, and if
1235 it's false (0) we want to eval the second. If the argument doesn't
1236 exist we do nothing, otherwise expand it and add to the buffer. */
1238 argv += 1 + !result;
1240 if (argv[0])
1242 char *expansion;
1244 expansion = expand_argument (argv[0], NULL);
1246 o = variable_buffer_output (o, expansion, strlen (expansion));
1248 free (expansion);
1251 return o;
1254 static char *
1255 func_wildcard (o, argv, funcname)
1256 char *o;
1257 char **argv;
1258 const char *funcname;
1261 #ifdef _AMIGA
1262 o = wildcard_expansion (argv[0], o);
1263 #else
1264 char *p = string_glob (argv[0]);
1265 o = variable_buffer_output (o, p, strlen (p));
1266 #endif
1267 return o;
1271 $(eval <makefile string>)
1273 Always resolves to the empty string.
1275 Treat the arguments as a segment of makefile, and parse them.
1278 static char *
1279 func_eval (o, argv, funcname)
1280 char *o;
1281 char **argv;
1282 const char *funcname;
1284 eval_buffer (argv[0]);
1286 return o;
1290 static char *
1291 func_value (o, argv, funcname)
1292 char *o;
1293 char **argv;
1294 const char *funcname;
1296 /* Look up the variable. */
1297 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1299 /* Copy its value into the output buffer without expanding it. */
1300 if (v)
1301 o = variable_buffer_output (o, v->value, strlen(v->value));
1303 return o;
1307 \r is replaced on UNIX as well. Is this desirable?
1309 void
1310 fold_newlines (buffer, length)
1311 char *buffer;
1312 int *length;
1314 char *dst = buffer;
1315 char *src = buffer;
1316 char *last_nonnl = buffer -1;
1317 src[*length] = 0;
1318 for (; *src != '\0'; ++src)
1320 if (src[0] == '\r' && src[1] == '\n')
1321 continue;
1322 if (*src == '\n')
1324 *dst++ = ' ';
1326 else
1328 last_nonnl = dst;
1329 *dst++ = *src;
1332 *(++last_nonnl) = '\0';
1333 *length = last_nonnl - buffer;
1338 int shell_function_pid = 0, shell_function_completed;
1341 #ifdef WINDOWS32
1342 /*untested*/
1344 #include <windows.h>
1345 #include <io.h>
1346 #include "sub_proc.h"
1349 void
1350 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1352 SECURITY_ATTRIBUTES saAttr;
1353 HANDLE hIn;
1354 HANDLE hErr;
1355 HANDLE hChildOutRd;
1356 HANDLE hChildOutWr;
1357 HANDLE hProcess;
1360 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1361 saAttr.bInheritHandle = TRUE;
1362 saAttr.lpSecurityDescriptor = NULL;
1364 if (DuplicateHandle (GetCurrentProcess(),
1365 GetStdHandle(STD_INPUT_HANDLE),
1366 GetCurrentProcess(),
1367 &hIn,
1369 TRUE,
1370 DUPLICATE_SAME_ACCESS) == FALSE) {
1371 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1372 GetLastError());
1375 if (DuplicateHandle(GetCurrentProcess(),
1376 GetStdHandle(STD_ERROR_HANDLE),
1377 GetCurrentProcess(),
1378 &hErr,
1380 TRUE,
1381 DUPLICATE_SAME_ACCESS) == FALSE) {
1382 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1383 GetLastError());
1386 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1387 fatal (NILF, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1389 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1391 if (!hProcess)
1392 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1394 /* make sure that CreateProcess() has Path it needs */
1395 sync_Path_environment();
1397 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1398 /* register process for wait */
1399 process_register(hProcess);
1401 /* set the pid for returning to caller */
1402 *pid_p = (int) hProcess;
1404 /* set up to read data from child */
1405 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1407 /* this will be closed almost right away */
1408 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1409 } else {
1410 /* reap/cleanup the failed process */
1411 process_cleanup(hProcess);
1413 /* close handles which were duplicated, they weren't used */
1414 CloseHandle(hIn);
1415 CloseHandle(hErr);
1417 /* close pipe handles, they won't be used */
1418 CloseHandle(hChildOutRd);
1419 CloseHandle(hChildOutWr);
1421 /* set status for return */
1422 pipedes[0] = pipedes[1] = -1;
1423 *pid_p = -1;
1426 #endif
1429 #ifdef __MSDOS__
1430 FILE *
1431 msdos_openpipe (int* pipedes, int *pidp, char *text)
1433 FILE *fpipe=0;
1434 /* MSDOS can't fork, but it has `popen'. */
1435 struct variable *sh = lookup_variable ("SHELL", 5);
1436 int e;
1437 extern int dos_command_running, dos_status;
1439 /* Make sure not to bother processing an empty line. */
1440 while (isblank ((unsigned char)*text))
1441 ++text;
1442 if (*text == '\0')
1443 return 0;
1445 if (sh)
1447 char buf[PATH_MAX + 7];
1448 /* This makes sure $SHELL value is used by $(shell), even
1449 though the target environment is not passed to it. */
1450 sprintf (buf, "SHELL=%s", sh->value);
1451 putenv (buf);
1454 e = errno;
1455 errno = 0;
1456 dos_command_running = 1;
1457 dos_status = 0;
1458 /* If dos_status becomes non-zero, it means the child process
1459 was interrupted by a signal, like SIGINT or SIGQUIT. See
1460 fatal_error_signal in commands.c. */
1461 fpipe = popen (text, "rt");
1462 dos_command_running = 0;
1463 if (!fpipe || dos_status)
1465 pipedes[0] = -1;
1466 *pidp = -1;
1467 if (dos_status)
1468 errno = EINTR;
1469 else if (errno == 0)
1470 errno = ENOMEM;
1471 shell_function_completed = -1;
1473 else
1475 pipedes[0] = fileno (fpipe);
1476 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1477 errno = e;
1478 shell_function_completed = 1;
1480 return fpipe;
1482 #endif
1485 Do shell spawning, with the naughty bits for different OSes.
1488 #ifdef VMS
1490 /* VMS can't do $(shell ...) */
1491 #define func_shell 0
1493 #else
1494 #ifndef _AMIGA
1495 static char *
1496 func_shell (o, argv, funcname)
1497 char *o;
1498 char **argv;
1499 const char *funcname;
1501 char* batch_filename = NULL;
1502 int i;
1504 #ifdef __MSDOS__
1505 FILE *fpipe;
1506 #endif
1507 char **command_argv;
1508 char *error_prefix;
1509 char **envp;
1510 int pipedes[2];
1511 int pid;
1513 #ifndef __MSDOS__
1514 /* Construct the argument list. */
1515 command_argv = construct_command_argv (argv[0],
1516 (char **) NULL, (struct file *) 0,
1517 &batch_filename);
1518 if (command_argv == 0)
1519 return o;
1520 #endif
1522 /* Using a target environment for `shell' loses in cases like:
1523 export var = $(shell echo foobie)
1524 because target_environment hits a loop trying to expand $(var)
1525 to put it in the environment. This is even more confusing when
1526 var was not explicitly exported, but just appeared in the
1527 calling environment. */
1529 envp = environ;
1531 /* For error messages. */
1532 if (reading_file != 0)
1534 error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1535 sprintf (error_prefix,
1536 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1538 else
1539 error_prefix = "";
1541 #ifdef WINDOWS32
1542 windows32_openpipe (pipedes, &pid, command_argv, envp);
1544 if (pipedes[0] < 0) {
1545 /* open of the pipe failed, mark as failed execution */
1546 shell_function_completed = -1;
1548 return o;
1549 } else
1550 #else /* WINDOWS32 */
1552 # ifdef __MSDOS__
1553 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1554 if (pipedes[0] < 0)
1556 perror_with_name (error_prefix, "pipe");
1557 return o;
1559 # else
1560 if (pipe (pipedes) < 0)
1562 perror_with_name (error_prefix, "pipe");
1563 return o;
1566 pid = vfork ();
1567 if (pid < 0)
1568 perror_with_name (error_prefix, "fork");
1569 else if (pid == 0)
1570 child_execute_job (0, pipedes[1], command_argv, envp);
1571 else
1572 # endif /* ! __MSDOS__ */
1574 #endif /* WINDOWS32 */
1576 /* We are the parent. */
1578 char *buffer;
1579 unsigned int maxlen;
1580 int cc;
1582 /* Record the PID for reap_children. */
1583 shell_function_pid = pid;
1584 #ifndef __MSDOS__
1585 shell_function_completed = 0;
1587 /* Free the storage only the child needed. */
1588 free (command_argv[0]);
1589 free ((char *) command_argv);
1591 /* Close the write side of the pipe. */
1592 (void) close (pipedes[1]);
1593 #endif
1595 /* Set up and read from the pipe. */
1597 maxlen = 200;
1598 buffer = (char *) xmalloc (maxlen + 1);
1600 /* Read from the pipe until it gets EOF. */
1601 for (i = 0; ; i += cc)
1603 if (i == maxlen)
1605 maxlen += 512;
1606 buffer = (char *) xrealloc (buffer, maxlen + 1);
1609 cc = read (pipedes[0], &buffer[i], maxlen - i);
1610 if (cc <= 0)
1611 break;
1613 buffer[i] = '\0';
1615 /* Close the read side of the pipe. */
1616 #ifdef __MSDOS__
1617 if (fpipe)
1618 (void) pclose (fpipe);
1619 #else
1620 (void) close (pipedes[0]);
1621 #endif
1623 /* Loop until child_handler sets shell_function_completed
1624 to the status of our child shell. */
1625 while (shell_function_completed == 0)
1626 reap_children (1, 0);
1628 if (batch_filename) {
1629 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1630 batch_filename));
1631 remove (batch_filename);
1632 free (batch_filename);
1634 shell_function_pid = 0;
1636 /* The child_handler function will set shell_function_completed
1637 to 1 when the child dies normally, or to -1 if it
1638 dies with status 127, which is most likely an exec fail. */
1640 if (shell_function_completed == -1)
1642 /* This most likely means that the execvp failed,
1643 so we should just write out the error message
1644 that came in over the pipe from the child. */
1645 fputs (buffer, stderr);
1646 fflush (stderr);
1648 else
1650 /* The child finished normally. Replace all
1651 newlines in its output with spaces, and put
1652 that in the variable output buffer. */
1653 fold_newlines (buffer, &i);
1654 o = variable_buffer_output (o, buffer, i);
1657 free (buffer);
1660 return o;
1663 #else /* _AMIGA */
1665 /* Do the Amiga version of func_shell. */
1667 static char *
1668 func_shell (char *o, char **argv, const char *funcname)
1670 /* Amiga can't fork nor spawn, but I can start a program with
1671 redirection of my choice. However, this means that we
1672 don't have an opportunity to reopen stdout to trap it. Thus,
1673 we save our own stdout onto a new descriptor and dup a temp
1674 file's descriptor onto our stdout temporarily. After we
1675 spawn the shell program, we dup our own stdout back to the
1676 stdout descriptor. The buffer reading is the same as above,
1677 except that we're now reading from a file. */
1679 #include <dos/dos.h>
1680 #include <proto/dos.h>
1682 BPTR child_stdout;
1683 char tmp_output[FILENAME_MAX];
1684 unsigned int maxlen = 200;
1685 int cc, i;
1686 char * buffer, * ptr;
1687 char ** aptr;
1688 int len = 0;
1689 char* batch_filename = NULL;
1691 /* Construct the argument list. */
1692 command_argv = construct_command_argv (argv[0], (char **) NULL,
1693 (struct file *) 0, &batch_filename);
1694 if (command_argv == 0)
1695 return o;
1697 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1698 Ideally we would use main.c:open_tmpfile(), but this uses a special
1699 Open(), not fopen(), and I'm not familiar enough with the code to mess
1700 with it. */
1701 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1702 mktemp (tmp_output);
1703 child_stdout = Open (tmp_output, MODE_NEWFILE);
1705 for (aptr=command_argv; *aptr; aptr++)
1706 len += strlen (*aptr) + 1;
1708 buffer = xmalloc (len + 1);
1709 ptr = buffer;
1711 for (aptr=command_argv; *aptr; aptr++)
1713 strcpy (ptr, *aptr);
1714 ptr += strlen (ptr) + 1;
1715 *ptr ++ = ' ';
1716 *ptr = 0;
1719 ptr[-1] = '\n';
1721 Execute (buffer, NULL, child_stdout);
1722 free (buffer);
1724 Close (child_stdout);
1726 child_stdout = Open (tmp_output, MODE_OLDFILE);
1728 buffer = xmalloc (maxlen);
1729 i = 0;
1732 if (i == maxlen)
1734 maxlen += 512;
1735 buffer = (char *) xrealloc (buffer, maxlen + 1);
1738 cc = Read (child_stdout, &buffer[i], maxlen - i);
1739 if (cc > 0)
1740 i += cc;
1741 } while (cc > 0);
1743 Close (child_stdout);
1745 fold_newlines (buffer, &i);
1746 o = variable_buffer_output (o, buffer, i);
1747 free (buffer);
1748 return o;
1750 #endif /* _AMIGA */
1751 #endif /* !VMS */
1753 #ifdef EXPERIMENTAL
1756 equality. Return is string-boolean, ie, the empty string is false.
1758 static char *
1759 func_eq (char* o, char **argv, char *funcname)
1761 int result = ! strcmp (argv[0], argv[1]);
1762 o = variable_buffer_output (o, result ? "1" : "", result);
1763 return o;
1768 string-boolean not operator.
1770 static char *
1771 func_not (char* o, char **argv, char *funcname)
1773 char * s = argv[0];
1774 int result = 0;
1775 while (isspace ((unsigned char)*s))
1776 s++;
1777 result = ! (*s);
1778 o = variable_buffer_output (o, result ? "1" : "", result);
1779 return o;
1781 #endif
1784 /* Lookup table for builtin functions.
1786 This doesn't have to be sorted; we use a straight lookup. We might gain
1787 some efficiency by moving most often used functions to the start of the
1788 table.
1790 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1791 comma-separated values are treated as arguments.
1793 EXPAND_ARGS means that all arguments should be expanded before invocation.
1794 Functions that do namespace tricks (foreach) don't automatically expand. */
1796 static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
1799 static struct function_table_entry function_table_init[] =
1801 /* Name/size */ /* MIN MAX EXP? Function */
1802 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
1803 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
1804 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
1805 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
1806 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
1807 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
1808 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
1809 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
1810 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
1811 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
1812 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
1813 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
1814 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
1815 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
1816 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
1817 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
1818 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
1819 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
1820 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
1821 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
1822 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
1823 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
1824 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
1825 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
1826 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
1827 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
1828 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
1829 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
1830 #ifdef EXPERIMENTAL
1831 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
1832 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
1833 #endif
1836 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1839 /* These must come after the definition of function_table. */
1841 static char *
1842 expand_builtin_function (o, argc, argv, entry_p)
1843 char *o;
1844 int argc;
1845 char **argv;
1846 struct function_table_entry *entry_p;
1848 if (argc < (int)entry_p->minimum_args)
1849 fatal (reading_file,
1850 _("Insufficient number of arguments (%d) to function `%s'"),
1851 argc, entry_p->name);
1853 /* I suppose technically some function could do something with no
1854 arguments, but so far none do, so just test it for all functions here
1855 rather than in each one. We can change it later if necessary. */
1857 if (!argc)
1858 return o;
1860 if (!entry_p->func_ptr)
1861 fatal (reading_file, _("Unimplemented on this platform: function `%s'"),
1862 entry_p->name);
1864 return entry_p->func_ptr (o, argv, entry_p->name);
1867 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1868 opening ( or { and is not null-terminated. If a function invocation
1869 is found, expand it into the buffer at *OP, updating *OP, incrementing
1870 *STRINGP past the reference and returning nonzero. If not, return zero. */
1873 handle_function (op, stringp)
1874 char **op;
1875 char **stringp;
1877 const struct function_table_entry *entry_p;
1878 char openparen = (*stringp)[0];
1879 char closeparen = openparen == '(' ? ')' : '}';
1880 char *beg;
1881 char *end;
1882 int count = 0;
1883 register char *p;
1884 char **argv, **argvp;
1885 int nargs;
1887 beg = *stringp + 1;
1889 entry_p = lookup_function (beg);
1891 if (!entry_p)
1892 return 0;
1894 /* We found a builtin function. Find the beginning of its arguments (skip
1895 whitespace after the name). */
1897 beg = next_token (beg + entry_p->len);
1899 /* Find the end of the function invocation, counting nested use of
1900 whichever kind of parens we use. Since we're looking, count commas
1901 to get a rough estimate of how many arguments we might have. The
1902 count might be high, but it'll never be low. */
1904 for (nargs=1, end=beg; *end != '\0'; ++end)
1905 if (*end == ',')
1906 ++nargs;
1907 else if (*end == openparen)
1908 ++count;
1909 else if (*end == closeparen && --count < 0)
1910 break;
1912 if (count >= 0)
1913 fatal (reading_file,
1914 _("unterminated call to function `%s': missing `%c'"),
1915 entry_p->name, closeparen);
1917 *stringp = end;
1919 /* Get some memory to store the arg pointers. */
1920 argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
1922 /* Chop the string into arguments, then a nul. As soon as we hit
1923 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1924 last argument.
1926 If we're expanding, store pointers to the expansion of each one. If
1927 not, make a duplicate of the string and point into that, nul-terminating
1928 each argument. */
1930 if (!entry_p->expand_args)
1932 int len = end - beg;
1934 p = xmalloc (len+1);
1935 memcpy (p, beg, len);
1936 p[len] = '\0';
1937 beg = p;
1938 end = beg + len;
1941 for (p=beg, nargs=0; p <= end; ++argvp)
1943 char *next;
1945 ++nargs;
1947 if (nargs == entry_p->maximum_args
1948 || (! (next = find_next_argument (openparen, closeparen, p, end))))
1949 next = end;
1951 if (entry_p->expand_args)
1952 *argvp = expand_argument (p, next);
1953 else
1955 *argvp = p;
1956 *next = '\0';
1959 p = next + 1;
1961 *argvp = NULL;
1963 /* Finally! Run the function... */
1964 *op = expand_builtin_function (*op, nargs, argv, entry_p);
1966 /* Free memory. */
1967 if (entry_p->expand_args)
1968 for (argvp=argv; *argvp != 0; ++argvp)
1969 free (*argvp);
1970 else
1971 free (beg);
1973 return 1;
1977 /* User-defined functions. Expand the first argument as either a builtin
1978 function or a make variable, in the context of the rest of the arguments
1979 assigned to $1, $2, ... $N. $0 is the name of the function. */
1981 static char *
1982 func_call (o, argv, funcname)
1983 char *o;
1984 char **argv;
1985 const char *funcname;
1987 char *fname;
1988 char *cp;
1989 char *body;
1990 int flen;
1991 int i;
1992 const struct function_table_entry *entry_p;
1993 struct variable *v;
1995 /* There is no way to define a variable with a space in the name, so strip
1996 leading and trailing whitespace as a favor to the user. */
1997 fname = argv[0];
1998 while (*fname != '\0' && isspace ((unsigned char)*fname))
1999 ++fname;
2001 cp = fname + strlen (fname) - 1;
2002 while (cp > fname && isspace ((unsigned char)*cp))
2003 --cp;
2004 cp[1] = '\0';
2006 /* Calling nothing is a no-op */
2007 if (*fname == '\0')
2008 return o;
2010 /* Are we invoking a builtin function? */
2012 entry_p = lookup_function (fname);
2014 if (entry_p)
2016 /* How many arguments do we have? */
2017 for (i=0; argv[i+1]; ++i)
2020 return expand_builtin_function (o, i, argv+1, entry_p);
2023 /* Not a builtin, so the first argument is the name of a variable to be
2024 expanded and interpreted as a function. Find it. */
2025 flen = strlen (fname);
2027 v = lookup_variable (fname, flen);
2029 if (v == 0)
2030 warn_undefined (fname, flen);
2032 if (v == 0 || *v->value == '\0')
2033 return o;
2035 body = (char *) alloca (flen + 4);
2036 body[0] = '$';
2037 body[1] = '(';
2038 memcpy (body + 2, fname, flen);
2039 body[flen+2] = ')';
2040 body[flen+3] = '\0';
2042 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2044 push_new_variable_scope ();
2046 for (i=0; *argv; ++i, ++argv)
2048 char num[11];
2050 sprintf (num, "%d", i);
2051 define_variable (num, strlen (num), *argv, o_automatic, 0);
2054 /* Expand the body in the context of the arguments, adding the result to
2055 the variable buffer. */
2057 v->exp_count = EXP_COUNT_MAX;
2059 o = variable_expand_string (o, body, flen+3);
2061 v->exp_count = 0;
2063 pop_variable_scope ();
2065 return o + strlen (o);
2068 void
2069 hash_init_function_table ()
2071 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2072 function_table_entry_hash_1, function_table_entry_hash_2,
2073 function_table_entry_hash_cmp);
2074 hash_load (&function_table, function_table_init,
2075 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));