Fix for complex situations where directories are declared as prerequisites.
[make.git] / function.c
blob06b23d2fff48cd3d56d24d38d30b4eb0ed31e85a
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 (void const *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 (void const *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 (void const *xv, void const *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 (o, text, subst, replace, slen, rlen, by_word, suffix_only)
80 char *o;
81 char *text;
82 char *subst, *replace;
83 unsigned int slen, rlen;
84 int by_word, suffix_only;
86 register char *t = text;
87 register char *p;
89 if (slen == 0 && !by_word && !suffix_only)
91 /* The first occurrence of "" in any string is its end. */
92 o = variable_buffer_output (o, t, strlen (t));
93 if (rlen > 0)
94 o = variable_buffer_output (o, replace, rlen);
95 return o;
100 if ((by_word | suffix_only) && slen == 0)
101 /* When matching by words, the empty string should match
102 the end of each word, rather than the end of the whole text. */
103 p = end_of_token (next_token (t));
104 else
106 p = sindex (t, 0, subst, slen);
107 if (p == 0)
109 /* No more matches. Output everything left on the end. */
110 o = variable_buffer_output (o, t, strlen (t));
111 return o;
115 /* Output everything before this occurrence of the string to replace. */
116 if (p > t)
117 o = variable_buffer_output (o, t, p - t);
119 /* If we're substituting only by fully matched words,
120 or only at the ends of words, check that this case qualifies. */
121 if ((by_word
122 && ((p > t && !isblank ((unsigned char)p[-1]))
123 || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
124 || (suffix_only
125 && (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
126 /* Struck out. Output the rest of the string that is
127 no longer to be replaced. */
128 o = variable_buffer_output (o, subst, slen);
129 else if (rlen > 0)
130 /* Output the replacement string. */
131 o = variable_buffer_output (o, replace, rlen);
133 /* Advance T past the string to be replaced. */
134 t = p + slen;
135 } while (*t != '\0');
137 return o;
141 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
142 and replacing strings matching PATTERN with REPLACE.
143 If PATTERN_PERCENT is not nil, PATTERN has already been
144 run through find_percent, and PATTERN_PERCENT is the result.
145 If REPLACE_PERCENT is not nil, REPLACE has already been
146 run through find_percent, and REPLACE_PERCENT is the result. */
148 char *
149 patsubst_expand (o, text, pattern, replace, pattern_percent, replace_percent)
150 char *o;
151 char *text;
152 register char *pattern, *replace;
153 register char *pattern_percent, *replace_percent;
155 unsigned int pattern_prepercent_len, pattern_postpercent_len;
156 unsigned int replace_prepercent_len, replace_postpercent_len = 0;
157 char *t;
158 unsigned int len;
159 int doneany = 0;
161 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
162 will be collapsed before we call subst_expand if PATTERN has no %. */
163 if (replace_percent == 0)
164 replace_percent = find_percent (replace);
165 if (replace_percent != 0)
167 /* Record the length of REPLACE before and after the % so
168 we don't have to compute these lengths more than once. */
169 replace_prepercent_len = replace_percent - replace;
170 replace_postpercent_len = strlen (replace_percent + 1);
172 else
173 /* We store the length of the replacement
174 so we only need to compute it once. */
175 replace_prepercent_len = strlen (replace);
177 if (pattern_percent == 0)
178 pattern_percent = find_percent (pattern);
179 if (pattern_percent == 0)
180 /* With no % in the pattern, this is just a simple substitution. */
181 return subst_expand (o, text, pattern, replace,
182 strlen (pattern), strlen (replace), 1, 0);
184 /* Record the length of PATTERN before and after the %
185 so we don't have to compute it more than once. */
186 pattern_prepercent_len = pattern_percent - pattern;
187 pattern_postpercent_len = strlen (pattern_percent + 1);
189 while ((t = find_next_token (&text, &len)) != 0)
191 int fail = 0;
193 /* Is it big enough to match? */
194 if (len < pattern_prepercent_len + pattern_postpercent_len)
195 fail = 1;
197 /* Does the prefix match? */
198 if (!fail && pattern_prepercent_len > 0
199 && (*t != *pattern
200 || t[pattern_prepercent_len - 1] != pattern_percent[-1]
201 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
202 fail = 1;
204 /* Does the suffix match? */
205 if (!fail && pattern_postpercent_len > 0
206 && (t[len - 1] != pattern_percent[pattern_postpercent_len]
207 || t[len - pattern_postpercent_len] != pattern_percent[1]
208 || !strneq (&t[len - pattern_postpercent_len],
209 &pattern_percent[1], pattern_postpercent_len - 1)))
210 fail = 1;
212 if (fail)
213 /* It didn't match. Output the string. */
214 o = variable_buffer_output (o, t, len);
215 else
217 /* It matched. Output the replacement. */
219 /* Output the part of the replacement before the %. */
220 o = variable_buffer_output (o, replace, replace_prepercent_len);
222 if (replace_percent != 0)
224 /* Output the part of the matched string that
225 matched the % in the pattern. */
226 o = variable_buffer_output (o, t + pattern_prepercent_len,
227 len - (pattern_prepercent_len
228 + pattern_postpercent_len));
229 /* Output the part of the replacement after the %. */
230 o = variable_buffer_output (o, replace_percent + 1,
231 replace_postpercent_len);
235 /* Output a space, but not if the replacement is "". */
236 if (fail || replace_prepercent_len > 0
237 || (replace_percent != 0 && len + replace_postpercent_len > 0))
239 o = variable_buffer_output (o, " ", 1);
240 doneany = 1;
243 if (doneany)
244 /* Kill the last space. */
245 --o;
247 return o;
251 /* Look up a function by name. */
253 static const struct function_table_entry *
254 lookup_function (s)
255 const char *s;
257 const char *e = s;
259 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
260 e++;
261 if (*e == '\0' || isblank ((unsigned char) *e))
263 struct function_table_entry function_table_entry_key;
264 function_table_entry_key.name = s;
265 function_table_entry_key.len = e - s;
267 return hash_find_item (&function_table, &function_table_entry_key);
269 return 0;
273 /* Return 1 if PATTERN matches STR, 0 if not. */
276 pattern_matches (pattern, percent, str)
277 register char *pattern, *percent, *str;
279 unsigned int sfxlen, strlength;
281 if (percent == 0)
283 unsigned int len = strlen (pattern) + 1;
284 char *new_chars = (char *) alloca (len);
285 bcopy (pattern, new_chars, len);
286 pattern = new_chars;
287 percent = find_percent (pattern);
288 if (percent == 0)
289 return streq (pattern, str);
292 sfxlen = strlen (percent + 1);
293 strlength = strlen (str);
295 if (strlength < (percent - pattern) + sfxlen
296 || !strneq (pattern, str, percent - pattern))
297 return 0;
299 return !strcmp (percent + 1, str + (strlength - sfxlen));
303 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
304 ENDPARENtheses), starting at PTR before END. Return a pointer to
305 next character.
307 If no next argument is found, return NULL.
310 static char *
311 find_next_argument (startparen, endparen, ptr, end)
312 char startparen;
313 char endparen;
314 const char *ptr;
315 const char *end;
317 int count = 0;
319 for (; ptr < end; ++ptr)
320 if (*ptr == startparen)
321 ++count;
323 else if (*ptr == endparen)
325 --count;
326 if (count < 0)
327 return NULL;
330 else if (*ptr == ',' && !count)
331 return (char *)ptr;
333 /* We didn't find anything. */
334 return NULL;
338 /* Glob-expand LINE. The returned pointer is
339 only good until the next call to string_glob. */
341 static char *
342 string_glob (line)
343 char *line;
345 static char *result = 0;
346 static unsigned int length;
347 register struct nameseq *chain;
348 register unsigned int idx;
350 chain = multi_glob (parse_file_seq
351 (&line, '\0', sizeof (struct nameseq),
352 /* We do not want parse_file_seq to strip `./'s.
353 That would break examples like:
354 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
356 sizeof (struct nameseq));
358 if (result == 0)
360 length = 100;
361 result = (char *) xmalloc (100);
364 idx = 0;
365 while (chain != 0)
367 register char *name = chain->name;
368 unsigned int len = strlen (name);
370 struct nameseq *next = chain->next;
371 free ((char *) chain);
372 chain = next;
374 /* multi_glob will pass names without globbing metacharacters
375 through as is, but we want only files that actually exist. */
376 if (file_exists_p (name))
378 if (idx + len + 1 > length)
380 length += (len + 1) * 2;
381 result = (char *) xrealloc (result, length);
383 bcopy (name, &result[idx], len);
384 idx += len;
385 result[idx++] = ' ';
388 free (name);
391 /* Kill the last space and terminate the string. */
392 if (idx == 0)
393 result[0] = '\0';
394 else
395 result[idx - 1] = '\0';
397 return result;
401 Builtin functions
404 static char *
405 func_patsubst (o, argv, funcname)
406 char *o;
407 char **argv;
408 const char *funcname;
410 o = patsubst_expand (o, argv[2], argv[0], argv[1], (char *) 0, (char *) 0);
411 return o;
415 static char *
416 func_join (o, argv, funcname)
417 char *o;
418 char **argv;
419 const char *funcname;
421 int doneany = 0;
423 /* Write each word of the first argument directly followed
424 by the corresponding word of the second argument.
425 If the two arguments have a different number of words,
426 the excess words are just output separated by blanks. */
427 register char *tp;
428 register char *pp;
429 char *list1_iterator = argv[0];
430 char *list2_iterator = argv[1];
433 unsigned int len1, len2;
435 tp = find_next_token (&list1_iterator, &len1);
436 if (tp != 0)
437 o = variable_buffer_output (o, tp, len1);
439 pp = find_next_token (&list2_iterator, &len2);
440 if (pp != 0)
441 o = variable_buffer_output (o, pp, len2);
443 if (tp != 0 || pp != 0)
445 o = variable_buffer_output (o, " ", 1);
446 doneany = 1;
449 while (tp != 0 || pp != 0);
450 if (doneany)
451 /* Kill the last blank. */
452 --o;
454 return o;
458 static char *
459 func_origin (o, argv, funcname)
460 char *o;
461 char **argv;
462 const char *funcname;
464 /* Expand the argument. */
465 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
466 if (v == 0)
467 o = variable_buffer_output (o, "undefined", 9);
468 else
469 switch (v->origin)
471 default:
472 case o_invalid:
473 abort ();
474 break;
475 case o_default:
476 o = variable_buffer_output (o, "default", 7);
477 break;
478 case o_env:
479 o = variable_buffer_output (o, "environment", 11);
480 break;
481 case o_file:
482 o = variable_buffer_output (o, "file", 4);
483 break;
484 case o_env_override:
485 o = variable_buffer_output (o, "environment override", 20);
486 break;
487 case o_command:
488 o = variable_buffer_output (o, "command line", 12);
489 break;
490 case o_override:
491 o = variable_buffer_output (o, "override", 8);
492 break;
493 case o_automatic:
494 o = variable_buffer_output (o, "automatic", 9);
495 break;
498 return o;
501 #ifdef VMS
502 # define IS_PATHSEP(c) ((c) == ']')
503 #else
504 # ifdef HAVE_DOS_PATHS
505 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
506 # else
507 # define IS_PATHSEP(c) ((c) == '/')
508 # endif
509 #endif
512 static char *
513 func_notdir_suffix (o, argv, funcname)
514 char *o;
515 char **argv;
516 const char *funcname;
518 /* Expand the argument. */
519 char *list_iterator = argv[0];
520 char *p2 =0;
521 int doneany =0;
522 unsigned int len=0;
524 int is_suffix = streq (funcname, "suffix");
525 int is_notdir = !is_suffix;
526 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
528 char *p = p2 + len;
531 while (p >= p2 && (!is_suffix || *p != '.'))
533 if (IS_PATHSEP (*p))
534 break;
535 --p;
538 if (p >= p2)
540 if (is_notdir)
541 ++p;
542 else if (*p != '.')
543 continue;
544 o = variable_buffer_output (o, p, len - (p - p2));
546 #ifdef HAVE_DOS_PATHS
547 /* Handle the case of "d:foo/bar". */
548 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
550 p = p2 + 2;
551 o = variable_buffer_output (o, p, len - (p - p2));
553 #endif
554 else if (is_notdir)
555 o = variable_buffer_output (o, p2, len);
557 if (is_notdir || p >= p2)
559 o = variable_buffer_output (o, " ", 1);
560 doneany = 1;
563 if (doneany)
564 /* Kill last space. */
565 --o;
568 return o;
573 static char *
574 func_basename_dir (o, argv, funcname)
575 char *o;
576 char **argv;
577 const char *funcname;
579 /* Expand the argument. */
580 char *p3 = argv[0];
581 char *p2=0;
582 int doneany=0;
583 unsigned int len=0;
584 char *p=0;
585 int is_basename= streq (funcname, "basename");
586 int is_dir= !is_basename;
588 while ((p2 = find_next_token (&p3, &len)) != 0)
590 p = p2 + len;
591 while (p >= p2 && (!is_basename || *p != '.'))
593 if (IS_PATHSEP (*p))
594 break;
595 --p;
598 if (p >= p2 && (is_dir))
599 o = variable_buffer_output (o, p2, ++p - p2);
600 else if (p >= p2 && (*p == '.'))
601 o = variable_buffer_output (o, p2, p - p2);
602 #ifdef HAVE_DOS_PATHS
603 /* Handle the "d:foobar" case */
604 else if (p2[0] && p2[1] == ':' && is_dir)
605 o = variable_buffer_output (o, p2, 2);
606 #endif
607 else if (is_dir)
608 #ifdef VMS
609 o = variable_buffer_output (o, "[]", 2);
610 #else
611 #ifndef _AMIGA
612 o = variable_buffer_output (o, "./", 2);
613 #else
614 ; /* Just a nop... */
615 #endif /* AMIGA */
616 #endif /* !VMS */
617 else
618 /* The entire name is the basename. */
619 o = variable_buffer_output (o, p2, len);
621 o = variable_buffer_output (o, " ", 1);
622 doneany = 1;
624 if (doneany)
625 /* Kill last space. */
626 --o;
629 return o;
632 static char *
633 func_addsuffix_addprefix (o, argv, funcname)
634 char *o;
635 char **argv;
636 const char *funcname;
638 int fixlen = strlen (argv[0]);
639 char *list_iterator = argv[1];
640 int is_addprefix = streq (funcname, "addprefix");
641 int is_addsuffix = !is_addprefix;
643 int doneany = 0;
644 char *p;
645 unsigned int len;
647 while ((p = find_next_token (&list_iterator, &len)) != 0)
649 if (is_addprefix)
650 o = variable_buffer_output (o, argv[0], fixlen);
651 o = variable_buffer_output (o, p, len);
652 if (is_addsuffix)
653 o = variable_buffer_output (o, argv[0], fixlen);
654 o = variable_buffer_output (o, " ", 1);
655 doneany = 1;
658 if (doneany)
659 /* Kill last space. */
660 --o;
662 return o;
665 static char *
666 func_subst (o, argv, funcname)
667 char *o;
668 char **argv;
669 const char *funcname;
671 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
672 strlen (argv[1]), 0, 0);
674 return o;
678 static char *
679 func_firstword (o, argv, funcname)
680 char *o;
681 char **argv;
682 const char *funcname;
684 unsigned int i;
685 char *words = argv[0]; /* Use a temp variable for find_next_token */
686 char *p = find_next_token (&words, &i);
688 if (p != 0)
689 o = variable_buffer_output (o, p, i);
691 return o;
695 static char *
696 func_words (o, argv, funcname)
697 char *o;
698 char **argv;
699 const char *funcname;
701 int i = 0;
702 char *word_iterator = argv[0];
703 char buf[20];
705 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
706 ++i;
708 sprintf (buf, "%d", i);
709 o = variable_buffer_output (o, buf, strlen (buf));
712 return o;
715 char *
716 strip_whitespace (begpp, endpp)
717 char **begpp;
718 char **endpp;
720 while (isspace ((unsigned char)**begpp) && *begpp <= *endpp)
721 (*begpp) ++;
722 while (isspace ((unsigned char)**endpp) && *endpp >= *begpp)
723 (*endpp) --;
724 return *begpp;
728 is_numeric (p)
729 char *p;
731 char *end = p + strlen (p) - 1;
732 char *beg = p;
733 strip_whitespace (&p, &end);
735 while (p <= end)
736 if (!ISDIGIT (*(p++))) /* ISDIGIT only evals its arg once: see make.h. */
737 return 0;
739 return (end - beg >= 0);
742 void
743 check_numeric (s, message)
744 char *s;
745 char *message;
747 if (!is_numeric (s))
748 fatal (reading_file, message);
753 static char *
754 func_word (o, argv, funcname)
755 char *o;
756 char **argv;
757 const char *funcname;
759 char *end_p=0;
760 int i=0;
761 char *p=0;
763 /* Check the first argument. */
764 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
765 i = atoi (argv[0]);
767 if (i == 0)
768 fatal (reading_file, _("first argument to `word' function must be greater than 0"));
771 end_p = argv[1];
772 while ((p = find_next_token (&end_p, 0)) != 0)
773 if (--i == 0)
774 break;
776 if (i == 0)
777 o = variable_buffer_output (o, p, end_p - p);
779 return o;
782 static char *
783 func_wordlist (o, argv, funcname)
784 char *o;
785 char **argv;
786 const char *funcname;
788 int start, count;
790 /* Check the arguments. */
791 check_numeric (argv[0],
792 _("non-numeric first argument to `wordlist' function"));
793 check_numeric (argv[1],
794 _("non-numeric second argument to `wordlist' function"));
796 start = atoi (argv[0]);
797 count = atoi (argv[1]) - start + 1;
799 if (count > 0)
801 char *p;
802 char *end_p = argv[2];
804 /* Find the beginning of the "start"th word. */
805 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
808 if (p)
810 /* Find the end of the "count"th word from start. */
811 while (--count && (find_next_token (&end_p, 0) != 0))
814 /* Return the stuff in the middle. */
815 o = variable_buffer_output (o, p, end_p - p);
819 return o;
822 static char*
823 func_findstring (o, argv, funcname)
824 char *o;
825 char **argv;
826 const char *funcname;
828 /* Find the first occurrence of the first string in the second. */
829 int i = strlen (argv[0]);
830 if (sindex (argv[1], 0, argv[0], i) != 0)
831 o = variable_buffer_output (o, argv[0], i);
833 return o;
836 static char *
837 func_foreach (o, argv, funcname)
838 char *o;
839 char **argv;
840 const char *funcname;
842 /* expand only the first two. */
843 char *varname = expand_argument (argv[0], NULL);
844 char *list = expand_argument (argv[1], NULL);
845 char *body = argv[2];
847 int doneany = 0;
848 char *list_iterator = list;
849 char *p;
850 unsigned int len;
851 register struct variable *var;
853 push_new_variable_scope ();
854 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
856 /* loop through LIST, put the value in VAR and expand BODY */
857 while ((p = find_next_token (&list_iterator, &len)) != 0)
859 char *result = 0;
862 char save = p[len];
864 p[len] = '\0';
865 free (var->value);
866 var->value = (char *) xstrdup ((char*) p);
867 p[len] = save;
870 result = allocated_variable_expand (body);
872 o = variable_buffer_output (o, result, strlen (result));
873 o = variable_buffer_output (o, " ", 1);
874 doneany = 1;
875 free (result);
878 if (doneany)
879 /* Kill the last space. */
880 --o;
882 pop_variable_scope ();
883 free (varname);
884 free (list);
886 return o;
889 struct a_word
891 struct a_word *next;
892 struct a_word *chain;
893 char *str;
894 int length;
895 int matched;
898 static unsigned long
899 a_word_hash_1 (void const *key)
901 return_STRING_HASH_1 (((struct a_word const *) key)->str);
904 static unsigned long
905 a_word_hash_2 (void const *key)
907 return_STRING_HASH_2 (((struct a_word const *) key)->str);
910 static int
911 a_word_hash_cmp (void const *x, void const *y)
913 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
914 if (result)
915 return result;
916 return_STRING_COMPARE (((struct a_word const *) x)->str,
917 ((struct a_word const *) y)->str);
920 struct a_pattern
922 struct a_pattern *next;
923 char *str;
924 char *percent;
925 int length;
926 int save_c;
929 static char *
930 func_filter_filterout (o, argv, funcname)
931 char *o;
932 char **argv;
933 const char *funcname;
935 struct a_word *wordhead;
936 struct a_word **wordtail;
937 struct a_word *wp;
938 struct a_pattern *pathead;
939 struct a_pattern **pattail;
940 struct a_pattern *pp;
942 struct hash_table a_word_table;
943 int is_filter = streq (funcname, "filter");
944 char *pat_iterator = argv[0];
945 char *word_iterator = argv[1];
946 int literals = 0;
947 int words = 0;
948 int hashing = 0;
949 char *p;
950 unsigned int len;
952 /* Chop ARGV[0] up into patterns to match against the words. */
954 pattail = &pathead;
955 while ((p = find_next_token (&pat_iterator, &len)) != 0)
957 struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
959 *pattail = pat;
960 pattail = &pat->next;
962 if (*pat_iterator != '\0')
963 ++pat_iterator;
965 pat->str = p;
966 pat->length = len;
967 pat->save_c = p[len];
968 p[len] = '\0';
969 pat->percent = find_percent (p);
970 if (pat->percent == 0)
971 literals++;
973 *pattail = 0;
975 /* Chop ARGV[1] up into words to match against the patterns. */
977 wordtail = &wordhead;
978 while ((p = find_next_token (&word_iterator, &len)) != 0)
980 struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
982 *wordtail = word;
983 wordtail = &word->next;
985 if (*word_iterator != '\0')
986 ++word_iterator;
988 p[len] = '\0';
989 word->str = p;
990 word->length = len;
991 word->matched = 0;
992 word->chain = 0;
993 words++;
995 *wordtail = 0;
997 /* Only use a hash table if arg list lengths justifies the cost. */
998 hashing = (literals >= 2 && (literals * words) >= 10);
999 if (hashing)
1001 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
1002 for (wp = wordhead; wp != 0; wp = wp->next)
1004 struct a_word *owp = hash_insert (&a_word_table, wp);
1005 if (owp)
1006 wp->chain = owp;
1010 if (words)
1012 int doneany = 0;
1014 /* Run each pattern through the words, killing words. */
1015 for (pp = pathead; pp != 0; pp = pp->next)
1017 if (pp->percent)
1018 for (wp = wordhead; wp != 0; wp = wp->next)
1019 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1020 else if (hashing)
1022 struct a_word a_word_key;
1023 a_word_key.str = pp->str;
1024 a_word_key.length = pp->length;
1025 wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
1026 while (wp)
1028 wp->matched |= 1;
1029 wp = wp->chain;
1032 else
1033 for (wp = wordhead; wp != 0; wp = wp->next)
1034 wp->matched |= (wp->length == pp->length
1035 && strneq (pp->str, wp->str, wp->length));
1038 /* Output the words that matched (or didn't, for filter-out). */
1039 for (wp = wordhead; wp != 0; wp = wp->next)
1040 if (is_filter ? wp->matched : !wp->matched)
1042 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1043 o = variable_buffer_output (o, " ", 1);
1044 doneany = 1;
1047 if (doneany)
1048 /* Kill the last space. */
1049 --o;
1052 for (pp = pathead; pp != 0; pp = pp->next)
1053 pp->str[pp->length] = pp->save_c;
1055 if (hashing)
1056 hash_free (&a_word_table, 0);
1058 return o;
1062 static char *
1063 func_strip (o, argv, funcname)
1064 char *o;
1065 char **argv;
1066 const char *funcname;
1068 char *p = argv[0];
1069 int doneany =0;
1071 while (*p != '\0')
1073 int i=0;
1074 char *word_start=0;
1076 while (isspace ((unsigned char)*p))
1077 ++p;
1078 word_start = p;
1079 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1081 if (!i)
1082 break;
1083 o = variable_buffer_output (o, word_start, i);
1084 o = variable_buffer_output (o, " ", 1);
1085 doneany = 1;
1088 if (doneany)
1089 /* Kill the last space. */
1090 --o;
1091 return o;
1095 Print a warning or fatal message.
1097 static char *
1098 func_error (o, argv, funcname)
1099 char *o;
1100 char **argv;
1101 const char *funcname;
1103 char **argvp;
1104 char *msg, *p;
1105 int len;
1107 /* The arguments will be broken on commas. Rather than create yet
1108 another special case where function arguments aren't broken up,
1109 just create a format string that puts them back together. */
1110 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1111 len += strlen (*argvp) + 2;
1113 p = msg = (char *) alloca (len + 1);
1115 for (argvp=argv; argvp[1] != 0; ++argvp)
1117 strcpy (p, *argvp);
1118 p += strlen (*argvp);
1119 *(p++) = ',';
1120 *(p++) = ' ';
1122 strcpy (p, *argvp);
1124 if (*funcname == 'e')
1125 fatal (reading_file, "%s", msg);
1127 /* The warning function expands to the empty string. */
1128 error (reading_file, "%s", msg);
1130 return o;
1135 chop argv[0] into words, and sort them.
1137 static char *
1138 func_sort (o, argv, funcname)
1139 char *o;
1140 char **argv;
1141 const char *funcname;
1143 char **words = 0;
1144 int nwords = 0;
1145 register int wordi = 0;
1147 /* Chop ARGV[0] into words and put them in WORDS. */
1148 char *t = argv[0];
1149 char *p;
1150 unsigned int len;
1151 int i;
1153 while ((p = find_next_token (&t, &len)) != 0)
1155 if (wordi >= nwords - 1)
1157 nwords = (2 * nwords) + 5;
1158 words = (char **) xrealloc ((char *) words,
1159 nwords * sizeof (char *));
1161 words[wordi++] = savestring (p, len);
1164 if (!wordi)
1165 return o;
1167 /* Now sort the list of words. */
1168 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1170 /* Now write the sorted list. */
1171 for (i = 0; i < wordi; ++i)
1173 len = strlen (words[i]);
1174 if (i == wordi - 1 || strlen (words[i + 1]) != len
1175 || strcmp (words[i], words[i + 1]))
1177 o = variable_buffer_output (o, words[i], len);
1178 o = variable_buffer_output (o, " ", 1);
1180 free (words[i]);
1182 /* Kill the last space. */
1183 --o;
1185 free (words);
1187 return o;
1191 $(if condition,true-part[,false-part])
1193 CONDITION is false iff it evaluates to an empty string. White
1194 space before and after condition are stripped before evaluation.
1196 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1197 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1198 you can use $(if ...) to create side-effects (with $(shell ...), for
1199 example).
1202 static char *
1203 func_if (o, argv, funcname)
1204 char *o;
1205 char **argv;
1206 const char *funcname;
1208 char *begp = argv[0];
1209 char *endp = begp + strlen (argv[0]);
1210 int result = 0;
1212 /* Find the result of the condition: if we have a value, and it's not
1213 empty, the condition is true. If we don't have a value, or it's the
1214 empty string, then it's false. */
1216 strip_whitespace (&begp, &endp);
1218 if (begp < endp)
1220 char *expansion = expand_argument (begp, NULL);
1222 result = strlen (expansion);
1223 free (expansion);
1226 /* If the result is true (1) we want to eval the first argument, and if
1227 it's false (0) we want to eval the second. If the argument doesn't
1228 exist we do nothing, otherwise expand it and add to the buffer. */
1230 argv += 1 + !result;
1232 if (argv[0])
1234 char *expansion;
1236 expansion = expand_argument (argv[0], NULL);
1238 o = variable_buffer_output (o, expansion, strlen (expansion));
1240 free (expansion);
1243 return o;
1246 static char *
1247 func_wildcard (o, argv, funcname)
1248 char *o;
1249 char **argv;
1250 const char *funcname;
1253 #ifdef _AMIGA
1254 o = wildcard_expansion (argv[0], o);
1255 #else
1256 char *p = string_glob (argv[0]);
1257 o = variable_buffer_output (o, p, strlen (p));
1258 #endif
1259 return o;
1263 $(eval <makefile string>)
1265 Always resolves to the empty string.
1267 Treat the arguments as a segment of makefile, and parse them.
1270 static char *
1271 func_eval (o, argv, funcname)
1272 char *o;
1273 char **argv;
1274 const char *funcname;
1276 eval_buffer (argv[0]);
1278 return o;
1282 static char *
1283 func_value (o, argv, funcname)
1284 char *o;
1285 char **argv;
1286 const char *funcname;
1288 /* Look up the variable. */
1289 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1291 /* Copy its value into the output buffer without expanding it. */
1292 if (v)
1293 o = variable_buffer_output (o, v->value, strlen(v->value));
1295 return o;
1299 \r is replaced on UNIX as well. Is this desirable?
1301 void
1302 fold_newlines (buffer, length)
1303 char *buffer;
1304 int *length;
1306 char *dst = buffer;
1307 char *src = buffer;
1308 char *last_nonnl = buffer -1;
1309 src[*length] = 0;
1310 for (; *src != '\0'; ++src)
1312 if (src[0] == '\r' && src[1] == '\n')
1313 continue;
1314 if (*src == '\n')
1316 *dst++ = ' ';
1318 else
1320 last_nonnl = dst;
1321 *dst++ = *src;
1324 *(++last_nonnl) = '\0';
1325 *length = last_nonnl - buffer;
1330 int shell_function_pid = 0, shell_function_completed;
1333 #ifdef WINDOWS32
1334 /*untested*/
1336 #include <windows.h>
1337 #include <io.h>
1338 #include "sub_proc.h"
1341 void
1342 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1344 SECURITY_ATTRIBUTES saAttr;
1345 HANDLE hIn;
1346 HANDLE hErr;
1347 HANDLE hChildOutRd;
1348 HANDLE hChildOutWr;
1349 HANDLE hProcess;
1352 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1353 saAttr.bInheritHandle = TRUE;
1354 saAttr.lpSecurityDescriptor = NULL;
1356 if (DuplicateHandle (GetCurrentProcess(),
1357 GetStdHandle(STD_INPUT_HANDLE),
1358 GetCurrentProcess(),
1359 &hIn,
1361 TRUE,
1362 DUPLICATE_SAME_ACCESS) == FALSE) {
1363 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1364 GetLastError());
1367 if (DuplicateHandle(GetCurrentProcess(),
1368 GetStdHandle(STD_ERROR_HANDLE),
1369 GetCurrentProcess(),
1370 &hErr,
1372 TRUE,
1373 DUPLICATE_SAME_ACCESS) == FALSE) {
1374 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1375 GetLastError());
1378 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1379 fatal (NILF, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1381 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1383 if (!hProcess)
1384 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1386 /* make sure that CreateProcess() has Path it needs */
1387 sync_Path_environment();
1389 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1390 /* register process for wait */
1391 process_register(hProcess);
1393 /* set the pid for returning to caller */
1394 *pid_p = (int) hProcess;
1396 /* set up to read data from child */
1397 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1399 /* this will be closed almost right away */
1400 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1401 } else {
1402 /* reap/cleanup the failed process */
1403 process_cleanup(hProcess);
1405 /* close handles which were duplicated, they weren't used */
1406 CloseHandle(hIn);
1407 CloseHandle(hErr);
1409 /* close pipe handles, they won't be used */
1410 CloseHandle(hChildOutRd);
1411 CloseHandle(hChildOutWr);
1413 /* set status for return */
1414 pipedes[0] = pipedes[1] = -1;
1415 *pid_p = -1;
1418 #endif
1421 #ifdef __MSDOS__
1422 FILE *
1423 msdos_openpipe (int* pipedes, int *pidp, char *text)
1425 FILE *fpipe=0;
1426 /* MSDOS can't fork, but it has `popen'. */
1427 struct variable *sh = lookup_variable ("SHELL", 5);
1428 int e;
1429 extern int dos_command_running, dos_status;
1431 /* Make sure not to bother processing an empty line. */
1432 while (isblank ((unsigned char)*text))
1433 ++text;
1434 if (*text == '\0')
1435 return 0;
1437 if (sh)
1439 char buf[PATH_MAX + 7];
1440 /* This makes sure $SHELL value is used by $(shell), even
1441 though the target environment is not passed to it. */
1442 sprintf (buf, "SHELL=%s", sh->value);
1443 putenv (buf);
1446 e = errno;
1447 errno = 0;
1448 dos_command_running = 1;
1449 dos_status = 0;
1450 /* If dos_status becomes non-zero, it means the child process
1451 was interrupted by a signal, like SIGINT or SIGQUIT. See
1452 fatal_error_signal in commands.c. */
1453 fpipe = popen (text, "rt");
1454 dos_command_running = 0;
1455 if (!fpipe || dos_status)
1457 pipedes[0] = -1;
1458 *pidp = -1;
1459 if (dos_status)
1460 errno = EINTR;
1461 else if (errno == 0)
1462 errno = ENOMEM;
1463 shell_function_completed = -1;
1465 else
1467 pipedes[0] = fileno (fpipe);
1468 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1469 errno = e;
1470 shell_function_completed = 1;
1472 return fpipe;
1474 #endif
1477 Do shell spawning, with the naughty bits for different OSes.
1480 #ifdef VMS
1482 /* VMS can't do $(shell ...) */
1483 #define func_shell 0
1485 #else
1486 #ifndef _AMIGA
1487 static char *
1488 func_shell (o, argv, funcname)
1489 char *o;
1490 char **argv;
1491 const char *funcname;
1493 char* batch_filename = NULL;
1494 int i;
1496 #ifdef __MSDOS__
1497 FILE *fpipe;
1498 #endif
1499 char **command_argv;
1500 char *error_prefix;
1501 char **envp;
1502 int pipedes[2];
1503 int pid;
1505 #ifndef __MSDOS__
1506 /* Construct the argument list. */
1507 command_argv = construct_command_argv (argv[0],
1508 (char **) NULL, (struct file *) 0,
1509 &batch_filename);
1510 if (command_argv == 0)
1511 return o;
1512 #endif
1514 /* Using a target environment for `shell' loses in cases like:
1515 export var = $(shell echo foobie)
1516 because target_environment hits a loop trying to expand $(var)
1517 to put it in the environment. This is even more confusing when
1518 var was not explicitly exported, but just appeared in the
1519 calling environment. */
1521 envp = environ;
1523 /* For error messages. */
1524 if (reading_file != 0)
1526 error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1527 sprintf (error_prefix,
1528 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1530 else
1531 error_prefix = "";
1533 #ifdef WINDOWS32
1534 windows32_openpipe (pipedes, &pid, command_argv, envp);
1536 if (pipedes[0] < 0) {
1537 /* open of the pipe failed, mark as failed execution */
1538 shell_function_completed = -1;
1540 return o;
1541 } else
1542 #else /* WINDOWS32 */
1544 # ifdef __MSDOS__
1545 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1546 if (pipedes[0] < 0)
1548 perror_with_name (error_prefix, "pipe");
1549 return o;
1551 # else
1552 if (pipe (pipedes) < 0)
1554 perror_with_name (error_prefix, "pipe");
1555 return o;
1558 pid = vfork ();
1559 if (pid < 0)
1560 perror_with_name (error_prefix, "fork");
1561 else if (pid == 0)
1562 child_execute_job (0, pipedes[1], command_argv, envp);
1563 else
1564 # endif /* ! __MSDOS__ */
1566 #endif /* WINDOWS32 */
1568 /* We are the parent. */
1570 char *buffer;
1571 unsigned int maxlen;
1572 int cc;
1574 /* Record the PID for reap_children. */
1575 shell_function_pid = pid;
1576 #ifndef __MSDOS__
1577 shell_function_completed = 0;
1579 /* Free the storage only the child needed. */
1580 free (command_argv[0]);
1581 free ((char *) command_argv);
1583 /* Close the write side of the pipe. */
1584 (void) close (pipedes[1]);
1585 #endif
1587 /* Set up and read from the pipe. */
1589 maxlen = 200;
1590 buffer = (char *) xmalloc (maxlen + 1);
1592 /* Read from the pipe until it gets EOF. */
1593 for (i = 0; ; i += cc)
1595 if (i == maxlen)
1597 maxlen += 512;
1598 buffer = (char *) xrealloc (buffer, maxlen + 1);
1601 cc = read (pipedes[0], &buffer[i], maxlen - i);
1602 if (cc <= 0)
1603 break;
1605 buffer[i] = '\0';
1607 /* Close the read side of the pipe. */
1608 #ifdef __MSDOS__
1609 if (fpipe)
1610 (void) pclose (fpipe);
1611 #else
1612 (void) close (pipedes[0]);
1613 #endif
1615 /* Loop until child_handler sets shell_function_completed
1616 to the status of our child shell. */
1617 while (shell_function_completed == 0)
1618 reap_children (1, 0);
1620 if (batch_filename) {
1621 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1622 batch_filename));
1623 remove (batch_filename);
1624 free (batch_filename);
1626 shell_function_pid = 0;
1628 /* The child_handler function will set shell_function_completed
1629 to 1 when the child dies normally, or to -1 if it
1630 dies with status 127, which is most likely an exec fail. */
1632 if (shell_function_completed == -1)
1634 /* This most likely means that the execvp failed,
1635 so we should just write out the error message
1636 that came in over the pipe from the child. */
1637 fputs (buffer, stderr);
1638 fflush (stderr);
1640 else
1642 /* The child finished normally. Replace all
1643 newlines in its output with spaces, and put
1644 that in the variable output buffer. */
1645 fold_newlines (buffer, &i);
1646 o = variable_buffer_output (o, buffer, i);
1649 free (buffer);
1652 return o;
1655 #else /* _AMIGA */
1657 /* Do the Amiga version of func_shell. */
1659 static char *
1660 func_shell (char *o, char **argv, const char *funcname)
1662 /* Amiga can't fork nor spawn, but I can start a program with
1663 redirection of my choice. However, this means that we
1664 don't have an opportunity to reopen stdout to trap it. Thus,
1665 we save our own stdout onto a new descriptor and dup a temp
1666 file's descriptor onto our stdout temporarily. After we
1667 spawn the shell program, we dup our own stdout back to the
1668 stdout descriptor. The buffer reading is the same as above,
1669 except that we're now reading from a file. */
1671 #include <dos/dos.h>
1672 #include <proto/dos.h>
1674 BPTR child_stdout;
1675 char tmp_output[FILENAME_MAX];
1676 unsigned int maxlen = 200;
1677 int cc, i;
1678 char * buffer, * ptr;
1679 char ** aptr;
1680 int len = 0;
1681 char* batch_filename = NULL;
1683 /* Construct the argument list. */
1684 command_argv = construct_command_argv (argv[0], (char **) NULL,
1685 (struct file *) 0, &batch_filename);
1686 if (command_argv == 0)
1687 return o;
1689 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1690 Ideally we would use main.c:open_tmpfile(), but this uses a special
1691 Open(), not fopen(), and I'm not familiar enough with the code to mess
1692 with it. */
1693 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1694 mktemp (tmp_output);
1695 child_stdout = Open (tmp_output, MODE_NEWFILE);
1697 for (aptr=command_argv; *aptr; aptr++)
1698 len += strlen (*aptr) + 1;
1700 buffer = xmalloc (len + 1);
1701 ptr = buffer;
1703 for (aptr=command_argv; *aptr; aptr++)
1705 strcpy (ptr, *aptr);
1706 ptr += strlen (ptr) + 1;
1707 *ptr ++ = ' ';
1708 *ptr = 0;
1711 ptr[-1] = '\n';
1713 Execute (buffer, NULL, child_stdout);
1714 free (buffer);
1716 Close (child_stdout);
1718 child_stdout = Open (tmp_output, MODE_OLDFILE);
1720 buffer = xmalloc (maxlen);
1721 i = 0;
1724 if (i == maxlen)
1726 maxlen += 512;
1727 buffer = (char *) xrealloc (buffer, maxlen + 1);
1730 cc = Read (child_stdout, &buffer[i], maxlen - i);
1731 if (cc > 0)
1732 i += cc;
1733 } while (cc > 0);
1735 Close (child_stdout);
1737 fold_newlines (buffer, &i);
1738 o = variable_buffer_output (o, buffer, i);
1739 free (buffer);
1740 return o;
1742 #endif /* _AMIGA */
1743 #endif /* !VMS */
1745 #ifdef EXPERIMENTAL
1748 equality. Return is string-boolean, ie, the empty string is false.
1750 static char *
1751 func_eq (char* o, char **argv, char *funcname)
1753 int result = ! strcmp (argv[0], argv[1]);
1754 o = variable_buffer_output (o, result ? "1" : "", result);
1755 return o;
1760 string-boolean not operator.
1762 static char *
1763 func_not (char* o, char **argv, char *funcname)
1765 char * s = argv[0];
1766 int result = 0;
1767 while (isspace ((unsigned char)*s))
1768 s++;
1769 result = ! (*s);
1770 o = variable_buffer_output (o, result ? "1" : "", result);
1771 return o;
1773 #endif
1776 /* Lookup table for builtin functions.
1778 This doesn't have to be sorted; we use a straight lookup. We might gain
1779 some efficiency by moving most often used functions to the start of the
1780 table.
1782 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1783 comma-separated values are treated as arguments.
1785 EXPAND_ARGS means that all arguments should be expanded before invocation.
1786 Functions that do namespace tricks (foreach) don't automatically expand. */
1788 static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
1791 static struct function_table_entry function_table_init[] =
1793 /* Name/size */ /* MIN MAX EXP? Function */
1794 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
1795 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
1796 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
1797 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
1798 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
1799 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
1800 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
1801 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
1802 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
1803 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
1804 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
1805 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
1806 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
1807 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
1808 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
1809 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
1810 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
1811 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
1812 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
1813 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
1814 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
1815 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
1816 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
1817 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
1818 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
1819 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
1820 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
1821 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
1822 #ifdef EXPERIMENTAL
1823 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
1824 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
1825 #endif
1828 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1831 /* These must come after the definition of function_table. */
1833 static char *
1834 expand_builtin_function (o, argc, argv, entry_p)
1835 char *o;
1836 int argc;
1837 char **argv;
1838 struct function_table_entry *entry_p;
1840 if (argc < entry_p->minimum_args)
1841 fatal (reading_file,
1842 _("Insufficient number of arguments (%d) to function `%s'"),
1843 argc, entry_p->name);
1845 /* I suppose technically some function could do something with no
1846 arguments, but so far none do, so just test it for all functions here
1847 rather than in each one. We can change it later if necessary. */
1849 if (!argc)
1850 return o;
1852 if (!entry_p->func_ptr)
1853 fatal (reading_file, _("Unimplemented on this platform: function `%s'"),
1854 entry_p->name);
1856 return entry_p->func_ptr (o, argv, entry_p->name);
1859 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1860 opening ( or { and is not null-terminated. If a function invocation
1861 is found, expand it into the buffer at *OP, updating *OP, incrementing
1862 *STRINGP past the reference and returning nonzero. If not, return zero. */
1865 handle_function (op, stringp)
1866 char **op;
1867 char **stringp;
1869 const struct function_table_entry *entry_p;
1870 char openparen = (*stringp)[0];
1871 char closeparen = openparen == '(' ? ')' : '}';
1872 char *beg;
1873 char *end;
1874 int count = 0;
1875 register char *p;
1876 char **argv, **argvp;
1877 int nargs;
1879 beg = *stringp + 1;
1881 entry_p = lookup_function (beg);
1883 if (!entry_p)
1884 return 0;
1886 /* We found a builtin function. Find the beginning of its arguments (skip
1887 whitespace after the name). */
1889 beg = next_token (beg + entry_p->len);
1891 /* Find the end of the function invocation, counting nested use of
1892 whichever kind of parens we use. Since we're looking, count commas
1893 to get a rough estimate of how many arguments we might have. The
1894 count might be high, but it'll never be low. */
1896 for (nargs=1, end=beg; *end != '\0'; ++end)
1897 if (*end == ',')
1898 ++nargs;
1899 else if (*end == openparen)
1900 ++count;
1901 else if (*end == closeparen && --count < 0)
1902 break;
1904 if (count >= 0)
1905 fatal (reading_file,
1906 _("unterminated call to function `%s': missing `%c'"),
1907 entry_p->name, closeparen);
1909 *stringp = end;
1911 /* Get some memory to store the arg pointers. */
1912 argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
1914 /* Chop the string into arguments, then a nul. As soon as we hit
1915 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1916 last argument.
1918 If we're expanding, store pointers to the expansion of each one. If
1919 not, make a duplicate of the string and point into that, nul-terminating
1920 each argument. */
1922 if (!entry_p->expand_args)
1924 int len = end - beg;
1926 p = xmalloc (len+1);
1927 memcpy (p, beg, len);
1928 p[len] = '\0';
1929 beg = p;
1930 end = beg + len;
1933 for (p=beg, nargs=0; p <= end; ++argvp)
1935 char *next;
1937 ++nargs;
1939 if (nargs == entry_p->maximum_args
1940 || (! (next = find_next_argument (openparen, closeparen, p, end))))
1941 next = end;
1943 if (entry_p->expand_args)
1944 *argvp = expand_argument (p, next);
1945 else
1947 *argvp = p;
1948 *next = '\0';
1951 p = next + 1;
1953 *argvp = NULL;
1955 /* Finally! Run the function... */
1956 *op = expand_builtin_function (*op, nargs, argv, entry_p);
1958 /* Free memory. */
1959 if (entry_p->expand_args)
1960 for (argvp=argv; *argvp != 0; ++argvp)
1961 free (*argvp);
1962 else
1963 free (beg);
1965 return 1;
1969 /* User-defined functions. Expand the first argument as either a builtin
1970 function or a make variable, in the context of the rest of the arguments
1971 assigned to $1, $2, ... $N. $0 is the name of the function. */
1973 static char *
1974 func_call (o, argv, funcname)
1975 char *o;
1976 char **argv;
1977 const char *funcname;
1979 char *fname;
1980 char *cp;
1981 char *body;
1982 int flen;
1983 int i;
1984 const struct function_table_entry *entry_p;
1985 struct variable *v;
1987 /* There is no way to define a variable with a space in the name, so strip
1988 leading and trailing whitespace as a favor to the user. */
1989 fname = argv[0];
1990 while (*fname != '\0' && isspace ((unsigned char)*fname))
1991 ++fname;
1993 cp = fname + strlen (fname) - 1;
1994 while (cp > fname && isspace ((unsigned char)*cp))
1995 --cp;
1996 cp[1] = '\0';
1998 /* Calling nothing is a no-op */
1999 if (*fname == '\0')
2000 return o;
2002 /* Are we invoking a builtin function? */
2004 entry_p = lookup_function (fname);
2006 if (entry_p)
2008 /* How many arguments do we have? */
2009 for (i=0; argv[i+1]; ++i)
2012 return expand_builtin_function (o, i, argv+1, entry_p);
2015 /* Not a builtin, so the first argument is the name of a variable to be
2016 expanded and interpreted as a function. Find it. */
2017 flen = strlen (fname);
2019 v = lookup_variable (fname, flen);
2021 if (v == 0)
2022 warn_undefined (fname, flen);
2024 if (v == 0 || *v->value == '\0')
2025 return o;
2027 body = (char *) alloca (flen + 4);
2028 body[0] = '$';
2029 body[1] = '(';
2030 memcpy (body + 2, fname, flen);
2031 body[flen+2] = ')';
2032 body[flen+3] = '\0';
2034 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2036 push_new_variable_scope ();
2038 for (i=0; *argv; ++i, ++argv)
2040 char num[11];
2042 sprintf (num, "%d", i);
2043 define_variable (num, strlen (num), *argv, o_automatic, 0);
2046 /* Expand the body in the context of the arguments, adding the result to
2047 the variable buffer. */
2049 v->exp_count = EXP_COUNT_MAX;
2051 o = variable_expand_string (o, body, flen+3);
2053 v->exp_count = 0;
2055 pop_variable_scope ();
2057 return o + strlen (o);
2060 void
2061 hash_init_function_table ()
2063 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2064 function_table_entry_hash_1, function_table_entry_hash_2,
2065 function_table_entry_hash_cmp);
2066 hash_load (&function_table, function_table_init,
2067 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));