* Add new debugging output level selection feature.
[make/kirr.git] / function.c
blob5ce56b5dd2004312cc92e17a00e928140213d217
1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988,89,91,92,93,94,95,96,97 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 int len;
37 int required_args;
38 int expand_args;
39 char *(*func_ptr) PARAMS((char *output, char **argv, const char*funcname));
43 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
44 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
45 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
46 nonzero, substitutions are done only on matches which are complete
47 whitespace-delimited words. If SUFFIX_ONLY is nonzero, substitutions are
48 done only at the ends of whitespace-delimited words. */
50 char *
51 subst_expand (o, text, subst, replace, slen, rlen, by_word, suffix_only)
52 char *o;
53 char *text;
54 char *subst, *replace;
55 unsigned int slen, rlen;
56 int by_word, suffix_only;
58 register char *t = text;
59 register char *p;
61 if (slen == 0 && !by_word && !suffix_only)
63 /* The first occurrence of "" in any string is its end. */
64 o = variable_buffer_output (o, t, strlen (t));
65 if (rlen > 0)
66 o = variable_buffer_output (o, replace, rlen);
67 return o;
72 if ((by_word | suffix_only) && slen == 0)
73 /* When matching by words, the empty string should match
74 the end of each word, rather than the end of the whole text. */
75 p = end_of_token (next_token (t));
76 else
78 p = sindex (t, 0, subst, slen);
79 if (p == 0)
81 /* No more matches. Output everything left on the end. */
82 o = variable_buffer_output (o, t, strlen (t));
83 return o;
87 /* Output everything before this occurrence of the string to replace. */
88 if (p > t)
89 o = variable_buffer_output (o, t, p - t);
91 /* If we're substituting only by fully matched words,
92 or only at the ends of words, check that this case qualifies. */
93 if ((by_word
94 && ((p > t && !isblank (p[-1]))
95 || (p[slen] != '\0' && !isblank (p[slen]))))
96 || (suffix_only
97 && (p[slen] != '\0' && !isblank (p[slen]))))
98 /* Struck out. Output the rest of the string that is
99 no longer to be replaced. */
100 o = variable_buffer_output (o, subst, slen);
101 else if (rlen > 0)
102 /* Output the replacement string. */
103 o = variable_buffer_output (o, replace, rlen);
105 /* Advance T past the string to be replaced. */
106 t = p + slen;
107 } while (*t != '\0');
109 return o;
113 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
114 and replacing strings matching PATTERN with REPLACE.
115 If PATTERN_PERCENT is not nil, PATTERN has already been
116 run through find_percent, and PATTERN_PERCENT is the result.
117 If REPLACE_PERCENT is not nil, REPLACE has already been
118 run through find_percent, and REPLACE_PERCENT is the result. */
120 char *
121 patsubst_expand (o, text, pattern, replace, pattern_percent, replace_percent)
122 char *o;
123 char *text;
124 register char *pattern, *replace;
125 register char *pattern_percent, *replace_percent;
127 unsigned int pattern_prepercent_len, pattern_postpercent_len;
128 unsigned int replace_prepercent_len, replace_postpercent_len = 0;
129 char *t;
130 unsigned int len;
131 int doneany = 0;
133 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
134 will be collapsed before we call subst_expand if PATTERN has no %. */
135 if (replace_percent == 0)
136 replace_percent = find_percent (replace);
137 if (replace_percent != 0)
139 /* Record the length of REPLACE before and after the % so
140 we don't have to compute these lengths more than once. */
141 replace_prepercent_len = replace_percent - replace;
142 replace_postpercent_len = strlen (replace_percent + 1);
144 else
145 /* We store the length of the replacement
146 so we only need to compute it once. */
147 replace_prepercent_len = strlen (replace);
149 if (pattern_percent == 0)
150 pattern_percent = find_percent (pattern);
151 if (pattern_percent == 0)
152 /* With no % in the pattern, this is just a simple substitution. */
153 return subst_expand (o, text, pattern, replace,
154 strlen (pattern), strlen (replace), 1, 0);
156 /* Record the length of PATTERN before and after the %
157 so we don't have to compute it more than once. */
158 pattern_prepercent_len = pattern_percent - pattern;
159 pattern_postpercent_len = strlen (pattern_percent + 1);
161 while ((t = find_next_token (&text, &len)) != 0)
163 int fail = 0;
165 /* Is it big enough to match? */
166 if (len < pattern_prepercent_len + pattern_postpercent_len)
167 fail = 1;
169 /* Does the prefix match? */
170 if (!fail && pattern_prepercent_len > 0
171 && (*t != *pattern
172 || t[pattern_prepercent_len - 1] != pattern_percent[-1]
173 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
174 fail = 1;
176 /* Does the suffix match? */
177 if (!fail && pattern_postpercent_len > 0
178 && (t[len - 1] != pattern_percent[pattern_postpercent_len]
179 || t[len - pattern_postpercent_len] != pattern_percent[1]
180 || !strneq (&t[len - pattern_postpercent_len],
181 &pattern_percent[1], pattern_postpercent_len - 1)))
182 fail = 1;
184 if (fail)
185 /* It didn't match. Output the string. */
186 o = variable_buffer_output (o, t, len);
187 else
189 /* It matched. Output the replacement. */
191 /* Output the part of the replacement before the %. */
192 o = variable_buffer_output (o, replace, replace_prepercent_len);
194 if (replace_percent != 0)
196 /* Output the part of the matched string that
197 matched the % in the pattern. */
198 o = variable_buffer_output (o, t + pattern_prepercent_len,
199 len - (pattern_prepercent_len
200 + pattern_postpercent_len));
201 /* Output the part of the replacement after the %. */
202 o = variable_buffer_output (o, replace_percent + 1,
203 replace_postpercent_len);
207 /* Output a space, but not if the replacement is "". */
208 if (fail || replace_prepercent_len > 0
209 || (replace_percent != 0 && len + replace_postpercent_len > 0))
211 o = variable_buffer_output (o, " ", 1);
212 doneany = 1;
215 if (doneany)
216 /* Kill the last space. */
217 --o;
219 return o;
223 /* Look up a function by name.
224 The table is currently small enough that it's not really worthwhile to use
225 a fancier lookup algorithm. If it gets larger, maybe...
228 static const struct function_table_entry *
229 lookup_function (table, s)
230 const struct function_table_entry *table;
231 const char *s;
233 int len = strlen(s);
235 for (; table->name != NULL; ++table)
236 if (table->len <= len
237 && (isblank (s[table->len]) || s[table->len] == '\0')
238 && strneq (s, table->name, table->len))
239 return table;
241 return NULL;
245 /* Return 1 if PATTERN matches STR, 0 if not. */
248 pattern_matches (pattern, percent, str)
249 register char *pattern, *percent, *str;
251 unsigned int sfxlen, strlength;
253 if (percent == 0)
255 unsigned int len = strlen (pattern) + 1;
256 char *new_chars = (char *) alloca (len);
257 bcopy (pattern, new_chars, len);
258 pattern = new_chars;
259 percent = find_percent (pattern);
260 if (percent == 0)
261 return streq (pattern, str);
264 sfxlen = strlen (percent + 1);
265 strlength = strlen (str);
267 if (strlength < (percent - pattern) + sfxlen
268 || !strneq (pattern, str, percent - pattern))
269 return 0;
271 return !strcmp (percent + 1, str + (strlength - sfxlen));
275 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
276 ENDPARENtheses), starting at PTR before END. Return a pointer to
277 next character.
279 If no next argument is found, return NULL.
282 static char *
283 find_next_argument (startparen, endparen, ptr, end)
284 char startparen;
285 char endparen;
286 const char *ptr;
287 const char *end;
289 int count = 0;
291 for (; ptr < end; ++ptr)
292 if (*ptr == startparen)
293 ++count;
295 else if (*ptr == endparen)
297 --count;
298 if (count < 0)
299 return NULL;
302 else if (*ptr == ',' && !count)
303 return (char *)ptr;
305 /* We didn't find anything. */
306 return NULL;
310 /* Glob-expand LINE. The returned pointer is
311 only good until the next call to string_glob. */
313 static char *
314 string_glob (line)
315 char *line;
317 static char *result = 0;
318 static unsigned int length;
319 register struct nameseq *chain;
320 register unsigned int idx;
322 chain = multi_glob (parse_file_seq
323 (&line, '\0', sizeof (struct nameseq),
324 /* We do not want parse_file_seq to strip `./'s.
325 That would break examples like:
326 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
328 sizeof (struct nameseq));
330 if (result == 0)
332 length = 100;
333 result = (char *) xmalloc (100);
336 idx = 0;
337 while (chain != 0)
339 register char *name = chain->name;
340 unsigned int len = strlen (name);
342 struct nameseq *next = chain->next;
343 free ((char *) chain);
344 chain = next;
346 /* multi_glob will pass names without globbing metacharacters
347 through as is, but we want only files that actually exist. */
348 if (file_exists_p (name))
350 if (idx + len + 1 > length)
352 length += (len + 1) * 2;
353 result = (char *) xrealloc (result, length);
355 bcopy (name, &result[idx], len);
356 idx += len;
357 result[idx++] = ' ';
360 free (name);
363 /* Kill the last space and terminate the string. */
364 if (idx == 0)
365 result[0] = '\0';
366 else
367 result[idx - 1] = '\0';
369 return result;
373 Builtin functions
376 static char *
377 func_patsubst (o, argv, funcname)
378 char *o;
379 char **argv;
380 const char *funcname;
382 o = patsubst_expand (o, argv[2], argv[0], argv[1], (char *) 0, (char *) 0);
383 return o;
387 static char *
388 func_join(o, argv, funcname)
389 char *o;
390 char **argv;
391 const char *funcname;
393 int doneany = 0;
395 /* Write each word of the first argument directly followed
396 by the corresponding word of the second argument.
397 If the two arguments have a different number of words,
398 the excess words are just output separated by blanks. */
399 register char *tp;
400 register char *pp;
401 char *list1_iterator = argv[0];
402 char *list2_iterator = argv[1];
405 unsigned int len1, len2;
407 tp = find_next_token (&list1_iterator, &len1);
408 if (tp != 0)
409 o = variable_buffer_output (o, tp, len1);
411 pp = find_next_token (&list2_iterator, &len2);
412 if (pp != 0)
413 o = variable_buffer_output (o, pp, len2);
415 if (tp != 0 || pp != 0)
417 o = variable_buffer_output (o, " ", 1);
418 doneany = 1;
421 while (tp != 0 || pp != 0);
422 if (doneany)
423 /* Kill the last blank. */
424 --o;
426 return o;
430 static char *
431 func_origin(o, argv, funcname)
432 char *o;
433 char **argv;
434 const char *funcname;
436 /* Expand the argument. */
437 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
438 if (v == 0)
439 o = variable_buffer_output (o, "undefined", 9);
440 else
441 switch (v->origin)
443 default:
444 case o_invalid:
445 abort ();
446 break;
447 case o_default:
448 o = variable_buffer_output (o, "default", 7);
449 break;
450 case o_env:
451 o = variable_buffer_output (o, "environment", 11);
452 break;
453 case o_file:
454 o = variable_buffer_output (o, "file", 4);
455 break;
456 case o_env_override:
457 o = variable_buffer_output (o, "environment override", 20);
458 break;
459 case o_command:
460 o = variable_buffer_output (o, "command line", 12);
461 break;
462 case o_override:
463 o = variable_buffer_output (o, "override", 8);
464 break;
465 case o_automatic:
466 o = variable_buffer_output (o, "automatic", 9);
467 break;
470 return o;
473 #ifdef VMS
474 #define IS_PATHSEP(c) ((c) == ']')
475 #else
476 #if defined(__MSDOS__) || defined(WINDOWS32)
477 #define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
478 #else
479 #define IS_PATHSEP(c) ((c) == '/')
480 #endif
481 #endif
484 static char *
485 func_notdir_suffix(o, argv, funcname)
486 char *o;
487 char **argv;
488 const char *funcname;
490 /* Expand the argument. */
491 char *list_iterator = argv[0];
492 char *p2 =0;
493 int doneany =0;
494 int len=0;
496 int is_suffix = streq(funcname, "suffix");
497 int is_notdir = !is_suffix;
498 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
500 char *p = p2 + len;
503 while (p >= p2 && (!is_suffix || *p != '.'))
505 if (IS_PATHSEP (*p))
506 break;
507 --p;
510 if (p >= p2)
512 if (is_notdir)
513 ++p;
514 else if (*p != '.')
515 continue;
516 o = variable_buffer_output (o, p, len - (p - p2));
518 #if defined(WINDOWS32) || defined(__MSDOS__)
519 /* Handle the case of "d:foo/bar". */
520 else if (streq(funcname, "notdir") && p2[0] && p2[1] == ':')
522 p = p2 + 2;
523 o = variable_buffer_output (o, p, len - (p - p2));
525 #endif
526 else if (is_notdir)
527 o = variable_buffer_output (o, p2, len);
529 if (is_notdir || p >= p2)
531 o = variable_buffer_output (o, " ", 1);
532 doneany = 1;
535 if (doneany)
536 /* Kill last space. */
537 --o;
540 return o;
545 static char *
546 func_basename_dir(o, argv, funcname)
547 char *o;
548 char **argv;
549 const char *funcname;
551 /* Expand the argument. */
552 char *p3 = argv[0];
553 char *p2=0;
554 int doneany=0;
555 unsigned int len=0;
556 char *p=0;
557 int is_basename= streq(funcname, "basename");
558 int is_dir= !is_basename;
560 while ((p2 = find_next_token (&p3, &len)) != 0)
562 p = p2 + len;
563 while (p >= p2 && (!is_basename || *p != '.'))
565 if (IS_PATHSEP(*p))
566 break;
567 --p;
570 if (p >= p2 && (is_dir))
571 o = variable_buffer_output (o, p2, ++p - p2);
572 else if (p >= p2 && (*p == '.'))
573 o = variable_buffer_output (o, p2, p - p2);
574 #if defined(WINDOWS32) || defined(__MSDOS__)
575 /* Handle the "d:foobar" case */
576 else if (p2[0] && p2[1] == ':' && is_dir)
577 o = variable_buffer_output (o, p2, 2);
578 #endif
579 else if (is_dir)
580 #ifdef VMS
581 o = variable_buffer_output (o, "[]", 2);
582 #else
583 #ifndef _AMIGA
584 o = variable_buffer_output (o, "./", 2);
585 #else
586 ; /* Just a nop... */
587 #endif /* AMIGA */
588 #endif /* !VMS */
589 else
590 /* The entire name is the basename. */
591 o = variable_buffer_output (o, p2, len);
593 o = variable_buffer_output (o, " ", 1);
594 doneany = 1;
596 if (doneany)
597 /* Kill last space. */
598 --o;
601 return o;
604 static char *
605 func_addsuffix_addprefix(o, argv, funcname)
606 char *o;
607 char **argv;
608 const char *funcname;
610 int fixlen = strlen (argv[0]);
611 char *list_iterator = argv[1];
612 int is_addprefix = streq (funcname, "addprefix");
613 int is_addsuffix = !is_addprefix;
615 int doneany = 0;
616 char *p;
617 unsigned int len;
619 while ((p = find_next_token (&list_iterator, &len)) != 0)
621 if (is_addprefix)
622 o = variable_buffer_output (o, argv[0], fixlen);
623 o = variable_buffer_output (o, p, len);
624 if (is_addsuffix)
625 o = variable_buffer_output (o, argv[0], fixlen);
626 o = variable_buffer_output (o, " ", 1);
627 doneany = 1;
630 if (doneany)
631 /* Kill last space. */
632 --o;
634 return o;
637 static char *
638 func_subst(o, argv, funcname)
639 char *o;
640 char **argv;
641 const char *funcname;
643 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
644 strlen (argv[1]), 0, 0);
646 return o;
650 static char *
651 func_firstword(o, argv, funcname)
652 char *o;
653 char **argv;
654 const char *funcname;
656 unsigned int i;
657 char *words = argv[0]; /* Use a temp variable for find_next_token */
658 char *p = find_next_token (&words, &i);
660 if (p != 0)
661 o = variable_buffer_output (o, p, i);
663 return o;
667 static char *
668 func_words(o, argv, funcname)
669 char *o;
670 char **argv;
671 const char *funcname;
673 int i = 0;
674 char *word_iterator = argv[0];
675 char buf[20];
677 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
678 ++i;
680 sprintf (buf, "%d", i);
681 o = variable_buffer_output (o, buf, strlen (buf));
684 return o;
687 char *
688 strip_whitespace (begpp, endpp)
689 char **begpp;
690 char **endpp;
692 while (isspace ((unsigned char)**begpp) && *begpp <= *endpp)
693 (*begpp) ++;
694 while (isspace ((unsigned char)**endpp) && *endpp >= *begpp)
695 (*endpp) --;
696 return *begpp;
700 is_numeric (p)
701 char *p;
703 char *end = p + strlen (p) - 1;
704 char *beg = p;
705 strip_whitespace (&p, &end);
707 while (p <= end)
708 if (!ISDIGIT (*(p++))) /* ISDIGIT only evals its arg once: see make.h. */
709 return 0;
711 return (end - beg >= 0);
714 void
715 check_numeric (s, message)
716 char *s;
717 char *message;
719 if (!is_numeric (s))
720 fatal (reading_file, message);
725 static char *
726 func_word(o, argv, funcname)
727 char *o;
728 char **argv;
729 const char *funcname;
731 char *end_p=0;
732 int i=0;
733 char *p=0;
735 /* Check the first argument. */
736 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
737 i = atoi (argv[0]);
739 if (i == 0)
740 fatal (reading_file, _("the `word' function takes a positive index argument"));
743 end_p = argv[1];
744 while ((p = find_next_token (&end_p, 0)) != 0)
745 if (--i == 0)
746 break;
748 if (i == 0)
749 o = variable_buffer_output (o, p, end_p - p);
751 return o;
754 static char *
755 func_wordlist (o, argv, funcname)
756 char *o;
757 char **argv;
758 const char *funcname;
760 int i=0;
761 int j=0;
763 /* Check the first argument. */
764 check_numeric (argv[0],
765 _("non-numeric first argument to `wordlist' function"));
766 i =atoi(argv[0]);
767 check_numeric (argv[1],
768 _("non-numeric second argument to `wordlist' function"));
770 j = atoi(argv[1]);
774 char *p;
775 char *end_p = argv[2];
777 int start = (i < j) ? i : j;
778 int count = j -i ;
779 if (count < 0)
780 count = - count;
781 count ++;
785 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
787 if (p)
789 while (--count && (find_next_token (&end_p, 0) != 0))
791 o = variable_buffer_output (o, p, end_p - p);
794 return o;
797 static char*
798 func_findstring(o, argv, funcname)
799 char *o;
800 char **argv;
801 const char *funcname;
803 /* Find the first occurrence of the first string in the second. */
804 int i = strlen (argv[0]);
805 if (sindex (argv[1], 0, argv[0], i) != 0)
806 o = variable_buffer_output (o, argv[0], i);
808 return o;
811 static char *
812 func_foreach (o, argv, funcname)
813 char *o;
814 char **argv;
815 const char *funcname;
817 /* expand only the first two. */
818 char *varname = expand_argument (argv[0], argv[1] - 1);
819 char *list = expand_argument (argv[1], argv[2] -1);
820 char *body = savestring (argv[2], argv[3] - argv[2] - 1);
822 int doneany = 0;
823 char *list_iterator = list;
824 char *p;
825 unsigned int len;
826 register struct variable *var;
828 push_new_variable_scope ();
829 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
831 /* loop through LIST, put the value in VAR and expand BODY */
832 while ((p = find_next_token (&list_iterator, &len)) != 0)
834 char *result = 0;
837 char save = p[len];
839 p[len] = '\0';
840 free (var->value);
841 var->value = (char *) xstrdup ((char*) p);
842 p[len] = save;
845 result = allocated_variable_expand (body);
847 o = variable_buffer_output (o, result, strlen (result));
848 o = variable_buffer_output (o, " ", 1);
849 doneany = 1;
850 free (result);
853 if (doneany)
854 /* Kill the last space. */
855 --o;
857 pop_variable_scope ();
858 free (varname);
859 free (list);
860 free (body);
862 return o;
865 struct a_word
867 struct a_word *next;
868 char *str;
869 int matched;
872 static char *
873 func_filter_filterout (o, argv, funcname)
874 char *o;
875 char **argv;
876 const char *funcname;
878 struct a_word *wordhead = 0;
879 struct a_word *wordtail = 0;
881 int is_filter = streq (funcname, "filter");
882 char *patterns = argv[0];
883 char *word_iterator = argv[1];
885 char *p;
886 unsigned int len;
888 /* Chop ARGV[1] up into words and then run each pattern through. */
889 while ((p = find_next_token (&word_iterator, &len)) != 0)
891 struct a_word *w = (struct a_word *)alloca(sizeof(struct a_word));
892 if (wordhead == 0)
893 wordhead = w;
894 else
895 wordtail->next = w;
896 wordtail = w;
898 if (*word_iterator != '\0')
899 ++word_iterator;
900 p[len] = '\0';
901 w->str = p;
902 w->matched = 0;
905 if (wordhead != 0)
907 char *pat_iterator = patterns;
908 int doneany = 0;
909 struct a_word *wp;
911 wordtail->next = 0;
913 /* Run each pattern through the words, killing words. */
914 while ((p = find_next_token (&pat_iterator, &len)) != 0)
916 char *percent;
917 char save = p[len];
918 p[len] = '\0';
920 percent = find_percent (p);
921 for (wp = wordhead; wp != 0; wp = wp->next)
922 wp->matched |= (percent == 0 ? streq (p, wp->str)
923 : pattern_matches (p, percent, wp->str));
925 p[len] = save;
928 /* Output the words that matched (or didn't, for filter-out). */
929 for (wp = wordhead; wp != 0; wp = wp->next)
930 if (is_filter ? wp->matched : !wp->matched)
932 o = variable_buffer_output (o, wp->str, strlen (wp->str));
933 o = variable_buffer_output (o, " ", 1);
934 doneany = 1;
937 if (doneany)
938 /* Kill the last space. */
939 --o;
942 return o;
946 static char *
947 func_strip(o, argv, funcname)
948 char *o;
949 char **argv;
950 const char *funcname;
952 char *p = argv[0];
953 int doneany =0;
955 while (*p != '\0')
957 int i=0;
958 char *word_start=0;
960 while (isspace ((unsigned char)*p))
961 ++p;
962 word_start = p;
963 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
965 if (!i)
966 break;
967 o = variable_buffer_output (o, word_start, i);
968 o = variable_buffer_output (o, " ", 1);
969 doneany = 1;
972 if (doneany)
973 /* Kill the last space. */
974 --o;
975 return o;
979 Print a warning or fatal message.
981 static char *
982 func_error (o, argv, funcname)
983 char *o;
984 char **argv;
985 const char *funcname;
987 char **argvp;
988 char *msg, *p;
989 int len;
991 /* The arguments will be broken on commas. Rather than create yet
992 another special case where function arguments aren't broken up,
993 just create a format string that puts them back together. */
994 for (len=0, argvp=argv; *argvp != 0; ++argvp)
995 len += strlen(*argvp) + 2;
997 p = msg = alloca (len + 1);
999 for (argvp=argv; argvp[1] != 0; ++argvp)
1001 strcpy(p, *argvp);
1002 p += strlen(*argvp);
1003 *(p++) = ',';
1004 *(p++) = ' ';
1006 strcpy(p, *argvp);
1008 if (*funcname == 'e')
1009 fatal (reading_file, "%s", msg);
1011 /* The warning function expands to the empty string. */
1012 error (reading_file, "%s", msg);
1014 return o;
1019 chop argv[0] into words, and sort them.
1021 static char *
1022 func_sort (o, argv, funcname)
1023 char *o;
1024 char **argv;
1025 const char *funcname;
1027 char **words = 0;
1028 int nwords = 0;
1029 register int wordi = 0;
1031 /* Chop ARGV[0] into words and put them in WORDS. */
1032 char *t = argv[0];
1033 char *p;
1034 unsigned int len;
1035 int i;
1037 while ((p = find_next_token (&t, &len)) != 0)
1039 if (wordi >= nwords - 1)
1041 nwords = (2 * nwords) + 5;
1042 words = (char **) xrealloc ((char *) words,
1043 nwords * sizeof (char *));
1045 words[wordi++] = savestring (p, len);
1048 if (!wordi)
1049 return o;
1051 /* Now sort the list of words. */
1052 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1054 /* Now write the sorted list. */
1055 for (i = 0; i < wordi; ++i)
1057 len = strlen (words[i]);
1058 if (i == wordi - 1 || strlen (words[i + 1]) != len
1059 || strcmp (words[i], words[i + 1]))
1061 o = variable_buffer_output (o, words[i], len);
1062 o = variable_buffer_output (o, " ", 1);
1064 free (words[i]);
1066 /* Kill the last space. */
1067 --o;
1069 free (words);
1071 return o;
1075 $(if condition,true-part[,false-part])
1077 CONDITION is false iff it evaluates to an empty string. White
1078 space before and after condition are stripped before evaluation.
1080 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1081 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1082 you can use $(if ...) to create side-effects (with $(shell ...), for
1083 example).
1086 static char *
1087 func_if (o, argv, funcname)
1088 char *o;
1089 char **argv;
1090 const char *funcname;
1092 char *begp = argv[0];
1093 char *endp = argv[1]-1;
1094 int result = 0;
1096 /* Find the result of the condition: if we have a value, and it's not
1097 empty, the condition is true. If we don't have a value, or it's the
1098 empty string, then it's false. */
1100 strip_whitespace (&begp, &endp);
1102 if (begp < endp)
1104 char *expansion = expand_argument (begp, endp);
1106 result = strlen (expansion);
1107 free (expansion);
1110 /* If the result is true (1) we want to eval the first argument, and if
1111 it's false (0) we want to eval the second. If the argument doesn't
1112 exist we do nothing, otherwise expand it and add to the buffer. */
1114 argv += 1 + !result;
1116 if (argv[0] != NULL && argv[1] != NULL)
1118 char *expansion;
1119 char **argend = argv+1;
1121 /* If we're doing the else-clause, make sure we concatenate any
1122 potential extra arguments into the last argument. */
1123 if (!result)
1124 while (argend[1])
1125 ++argend;
1127 expansion = expand_argument (*argv, *argend-1);
1129 o = variable_buffer_output (o, expansion, strlen (expansion));
1130 free (expansion);
1133 return o;
1136 static char *
1137 func_wildcard(o, argv, funcname)
1138 char *o;
1139 char **argv;
1140 const char *funcname;
1143 #ifdef _AMIGA
1144 o = wildcard_expansion (argv[0], o);
1145 #else
1146 char *p = string_glob (argv[0]);
1147 o = variable_buffer_output (o, p, strlen (p));
1148 #endif
1149 return o;
1153 \r is replaced on UNIX as well. Is this desirable?
1155 void
1156 fold_newlines (buffer, length)
1157 char *buffer;
1158 int *length;
1160 char *dst = buffer;
1161 char *src = buffer;
1162 char *last_nonnl = buffer -1;
1163 src[*length] = 0;
1164 for (; *src != '\0'; ++src)
1166 if (src[0] == '\r' && src[1] == '\n')
1167 continue;
1168 if (*src == '\n')
1170 *dst++ = ' ';
1172 else
1174 last_nonnl = dst;
1175 *dst++ = *src;
1178 *(++last_nonnl) = '\0';
1179 *length = last_nonnl - buffer;
1184 int shell_function_pid = 0, shell_function_completed;
1187 #ifdef WINDOWS32
1188 /*untested*/
1190 #include <windows.h>
1191 #include <io.h>
1192 #include "sub_proc.h"
1195 void
1196 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1198 SECURITY_ATTRIBUTES saAttr;
1199 HANDLE hIn;
1200 HANDLE hErr;
1201 HANDLE hChildOutRd;
1202 HANDLE hChildOutWr;
1203 HANDLE hProcess;
1206 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1207 saAttr.bInheritHandle = TRUE;
1208 saAttr.lpSecurityDescriptor = NULL;
1210 if (DuplicateHandle(GetCurrentProcess(),
1211 GetStdHandle(STD_INPUT_HANDLE),
1212 GetCurrentProcess(),
1213 &hIn,
1215 TRUE,
1216 DUPLICATE_SAME_ACCESS) == FALSE) {
1217 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1218 GetLastError());
1221 if (DuplicateHandle(GetCurrentProcess(),
1222 GetStdHandle(STD_ERROR_HANDLE),
1223 GetCurrentProcess(),
1224 &hErr,
1226 TRUE,
1227 DUPLICATE_SAME_ACCESS) == FALSE) {
1228 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1229 GetLastError());
1232 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1233 fatal (NILF, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1237 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1239 if (!hProcess)
1240 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1242 else
1243 process_register(hProcess);
1245 /* make sure that CreateProcess() has Path it needs */
1246 sync_Path_environment();
1248 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL))
1249 *pid_p = (int) hProcess;
1250 else
1251 fatal (NILF, _("windows32_openpipe (): unable to launch process (e=%d)\n"),
1252 process_last_err(hProcess));
1254 /* set up to read data from child */
1255 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1257 /* this will be closed almost right away */
1258 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1260 #endif
1263 #ifdef __MSDOS__
1264 FILE *
1265 msdos_openpipe (int* pipedes, int *pidp, char *text)
1267 FILE *fpipe=0;
1268 /* MSDOS can't fork, but it has `popen'. */
1269 struct variable *sh = lookup_variable ("SHELL", 5);
1270 int e;
1271 extern int dos_command_running, dos_status;
1273 /* Make sure not to bother processing an empty line. */
1274 while (isblank (*text))
1275 ++text;
1276 if (*text == '\0')
1277 return 0;
1279 if (sh)
1281 char buf[PATH_MAX + 7];
1282 /* This makes sure $SHELL value is used by $(shell), even
1283 though the target environment is not passed to it. */
1284 sprintf (buf, "SHELL=%s", sh->value);
1285 putenv (buf);
1288 e = errno;
1289 errno = 0;
1290 dos_command_running = 1;
1291 dos_status = 0;
1292 /* If dos_status becomes non-zero, it means the child process
1293 was interrupted by a signal, like SIGINT or SIGQUIT. See
1294 fatal_error_signal in commands.c. */
1295 fpipe = popen (text, "rt");
1296 dos_command_running = 0;
1297 if (!fpipe || dos_status)
1299 pipedes[0] = -1;
1300 *pidp = -1;
1301 if (dos_status)
1302 errno = EINTR;
1303 else if (errno == 0)
1304 errno = ENOMEM;
1305 shell_function_completed = -1;
1307 else
1309 pipedes[0] = fileno (fpipe);
1310 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1311 errno = e;
1312 shell_function_completed = 1;
1314 return fpipe;
1316 #endif
1319 Do shell spawning, with the naughty bits for different OSes.
1322 #ifdef VMS
1324 /* VMS can't do $(shell ...) */
1325 #define func_shell 0
1327 #else
1328 #ifndef _AMIGA
1329 static char *
1330 func_shell (o, argv, funcname)
1331 char *o;
1332 char **argv;
1333 const char *funcname;
1335 char* batch_filename = NULL;
1336 int i;
1338 #ifdef __MSDOS__
1339 FILE *fpipe;
1340 #endif
1341 char **command_argv;
1342 char *error_prefix;
1343 char **envp;
1344 int pipedes[2];
1345 int pid;
1347 #ifndef __MSDOS__
1348 /* Construct the argument list. */
1349 command_argv = construct_command_argv (argv[0],
1350 (char **) NULL, (struct file *) 0,
1351 &batch_filename);
1352 if (command_argv == 0)
1353 return o;
1354 #endif
1356 /* Using a target environment for `shell' loses in cases like:
1357 export var = $(shell echo foobie)
1358 because target_environment hits a loop trying to expand $(var)
1359 to put it in the environment. This is even more confusing when
1360 var was not explicitly exported, but just appeared in the
1361 calling environment. */
1363 envp = environ;
1365 /* For error messages. */
1366 if (reading_file != 0)
1368 error_prefix = (char *) alloca (strlen(reading_file->filenm)+11+4);
1369 sprintf (error_prefix,
1370 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1372 else
1373 error_prefix = "";
1375 #ifdef WINDOWS32
1376 windows32_openpipe (pipedes, &pid, command_argv, envp);
1377 #else /* WINDOWS32 */
1379 # ifdef __MSDOS__
1380 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1381 if (pipedes[0] < 0)
1383 perror_with_name (error_prefix, "pipe");
1384 return o;
1386 # else
1387 if (pipe (pipedes) < 0)
1389 perror_with_name (error_prefix, "pipe");
1390 return o;
1393 pid = vfork ();
1394 if (pid < 0)
1395 perror_with_name (error_prefix, "fork");
1396 else if (pid == 0)
1397 child_execute_job (0, pipedes[1], command_argv, envp);
1398 else
1399 # endif /* ! __MSDOS__ */
1401 #endif /* WINDOWS32 */
1403 /* We are the parent. */
1405 char *buffer;
1406 unsigned int maxlen;
1407 int cc;
1409 /* Record the PID for reap_children. */
1410 shell_function_pid = pid;
1411 #ifndef __MSDOS__
1412 shell_function_completed = 0;
1414 /* Free the storage only the child needed. */
1415 free (command_argv[0]);
1416 free ((char *) command_argv);
1418 /* Close the write side of the pipe. */
1419 (void) close (pipedes[1]);
1420 #endif
1422 /* Set up and read from the pipe. */
1424 maxlen = 200;
1425 buffer = (char *) xmalloc (maxlen + 1);
1427 /* Read from the pipe until it gets EOF. */
1428 i = 0;
1431 if (i == maxlen)
1433 maxlen += 512;
1434 buffer = (char *) xrealloc (buffer, maxlen + 1);
1437 errno = 0;
1438 cc = read (pipedes[0], &buffer[i], maxlen - i);
1439 if (cc > 0)
1440 i += cc;
1442 while (cc > 0 || EINTR_SET);
1444 /* Close the read side of the pipe. */
1445 #ifdef __MSDOS__
1446 if (fpipe)
1447 (void) pclose (fpipe);
1448 #else
1449 (void) close (pipedes[0]);
1450 #endif
1452 /* Loop until child_handler sets shell_function_completed
1453 to the status of our child shell. */
1454 while (shell_function_completed == 0)
1455 reap_children (1, 0);
1457 if (batch_filename) {
1458 DB (DB_EXTRA, (_("Cleaning up temporary batch file %s\n"),
1459 batch_filename));
1460 remove(batch_filename);
1461 free(batch_filename);
1463 shell_function_pid = 0;
1465 /* The child_handler function will set shell_function_completed
1466 to 1 when the child dies normally, or to -1 if it
1467 dies with status 127, which is most likely an exec fail. */
1469 if (shell_function_completed == -1)
1471 /* This most likely means that the execvp failed,
1472 so we should just write out the error message
1473 that came in over the pipe from the child. */
1474 fputs (buffer, stderr);
1475 fflush (stderr);
1477 else
1479 /* The child finished normally. Replace all
1480 newlines in its output with spaces, and put
1481 that in the variable output buffer. */
1482 fold_newlines (buffer, &i);
1483 o = variable_buffer_output (o, buffer, i);
1486 free (buffer);
1489 return o;
1492 #else /* _AMIGA */
1494 /* Do the Amiga version of func_shell. */
1496 static char *
1497 func_shell (char *o, char **argv, const char *funcname)
1499 /* Amiga can't fork nor spawn, but I can start a program with
1500 redirection of my choice. However, this means that we
1501 don't have an opportunity to reopen stdout to trap it. Thus,
1502 we save our own stdout onto a new descriptor and dup a temp
1503 file's descriptor onto our stdout temporarily. After we
1504 spawn the shell program, we dup our own stdout back to the
1505 stdout descriptor. The buffer reading is the same as above,
1506 except that we're now reading from a file. */
1508 #include <dos/dos.h>
1509 #include <proto/dos.h>
1511 BPTR child_stdout;
1512 char tmp_output[FILENAME_MAX];
1513 unsigned int maxlen = 200;
1514 int cc, i;
1515 char * buffer, * ptr;
1516 char ** aptr;
1517 int len = 0;
1518 char* batch_filename = NULL;
1520 /* Construct the argument list. */
1521 command_argv = construct_command_argv (argv[0], (char **) NULL,
1522 (struct file *) 0, &batch_filename);
1523 if (command_argv == 0)
1524 return o;
1527 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1528 mktemp (tmp_output);
1529 child_stdout = Open (tmp_output, MODE_NEWFILE);
1531 for (aptr=command_argv; *aptr; aptr++)
1532 len += strlen (*aptr) + 1;
1534 buffer = xmalloc (len + 1);
1535 ptr = buffer;
1537 for (aptr=command_argv; *aptr; aptr++)
1539 strcpy (ptr, *aptr);
1540 ptr += strlen (ptr) + 1;
1541 *ptr ++ = ' ';
1542 *ptr = 0;
1545 ptr[-1] = '\n';
1547 Execute (buffer, NULL, child_stdout);
1548 free (buffer);
1550 Close (child_stdout);
1552 child_stdout = Open (tmp_output, MODE_OLDFILE);
1554 buffer = xmalloc (maxlen);
1555 i = 0;
1558 if (i == maxlen)
1560 maxlen += 512;
1561 buffer = (char *) xrealloc (buffer, maxlen + 1);
1564 cc = Read (child_stdout, &buffer[i], maxlen - i);
1565 if (cc > 0)
1566 i += cc;
1567 } while (cc > 0);
1569 Close (child_stdout);
1571 fold_newlines (buffer, &i);
1572 o = variable_buffer_output (o, buffer, i);
1573 free (buffer);
1574 return o;
1576 #endif /* _AMIGA */
1577 #endif /* !VMS */
1579 #ifdef EXPERIMENTAL
1582 equality. Return is string-boolean, ie, the empty string is false.
1584 static char *
1585 func_eq (char* o, char **argv, char *funcname)
1587 int result = ! strcmp (argv[0], argv[1]);
1588 o = variable_buffer_output (o, result ? "1" : "", result);
1589 return o;
1594 string-boolean not operator.
1596 static char *
1597 func_not (char* o, char **argv, char *funcname)
1599 char * s = argv[0];
1600 int result = 0;
1601 while (isspace ((unsigned char)*s))
1602 s++;
1603 result = ! (*s);
1604 o = variable_buffer_output (o, result ? "1" : "", result);
1605 return o;
1607 #endif
1610 #define STRING_SIZE_TUPLE(_s) (_s), (sizeof(_s)-1)
1612 /* Lookup table for builtin functions.
1614 This doesn't have to be sorted; we use a straight lookup. We might gain
1615 some efficiency by moving most often used functions to the start of the
1616 table.
1618 If REQUIRED_ARGS is positive, the function takes exactly that many
1619 arguments. All subsequent text is included with the last argument. So,
1620 since $(sort a,b,c) takes only one argument, it will be the full string
1621 "a,b,c". If the value is negative, it's the minimum number of arguments.
1622 A function can have more, but if it has less an error is generated.
1624 EXPAND_ARGS means that all arguments should be expanded before invocation.
1625 Functions that do namespace tricks (foreach) don't automatically expand. */
1627 static char *func_call PARAMS((char *o, char **argv, const char *funcname));
1630 static struct function_table_entry function_table[] =
1632 /* Name/size */ /* ARG EXP? Function */
1633 { STRING_SIZE_TUPLE("addprefix"), 2, 1, func_addsuffix_addprefix},
1634 { STRING_SIZE_TUPLE("addsuffix"), 2, 1, func_addsuffix_addprefix},
1635 { STRING_SIZE_TUPLE("basename"), 1, 1, func_basename_dir},
1636 { STRING_SIZE_TUPLE("dir"), 1, 1, func_basename_dir},
1637 { STRING_SIZE_TUPLE("notdir"), 1, 1, func_notdir_suffix},
1638 { STRING_SIZE_TUPLE("subst"), 3, 1, func_subst},
1639 { STRING_SIZE_TUPLE("suffix"), 1, 1, func_notdir_suffix},
1640 { STRING_SIZE_TUPLE("filter"), 2, 1, func_filter_filterout},
1641 { STRING_SIZE_TUPLE("filter-out"), 2, 1, func_filter_filterout},
1642 { STRING_SIZE_TUPLE("findstring"), 2, 1, func_findstring},
1643 { STRING_SIZE_TUPLE("firstword"), 1, 1, func_firstword},
1644 { STRING_SIZE_TUPLE("join"), 2, 1, func_join},
1645 { STRING_SIZE_TUPLE("patsubst"), 3, 1, func_patsubst},
1646 { STRING_SIZE_TUPLE("shell"), 1, 1, func_shell},
1647 { STRING_SIZE_TUPLE("sort"), 1, 1, func_sort},
1648 { STRING_SIZE_TUPLE("strip"), 1, 1, func_strip},
1649 { STRING_SIZE_TUPLE("wildcard"), 1, 1, func_wildcard},
1650 { STRING_SIZE_TUPLE("word"), 2, 1, func_word},
1651 { STRING_SIZE_TUPLE("wordlist"), 3, 1, func_wordlist},
1652 { STRING_SIZE_TUPLE("words"), 1, 1, func_words},
1653 { STRING_SIZE_TUPLE("origin"), 1, 1, func_origin},
1654 { STRING_SIZE_TUPLE("foreach"), 3, 0, func_foreach},
1655 { STRING_SIZE_TUPLE("call"), -1, 1, func_call},
1656 { STRING_SIZE_TUPLE("error"), 1, 1, func_error},
1657 { STRING_SIZE_TUPLE("warning"), 1, 1, func_error},
1658 { STRING_SIZE_TUPLE("if"), -2, 0, func_if},
1659 #ifdef EXPERIMENTAL
1660 { STRING_SIZE_TUPLE("eq"), 2, 1, func_eq},
1661 { STRING_SIZE_TUPLE("not"), 1, 1, func_not},
1662 #endif
1663 { 0 }
1667 /* These must come after the definition of function_table[]. */
1669 static char *
1670 expand_builtin_function (o, argc, argv, entry_p)
1671 char *o;
1672 int argc;
1673 char **argv;
1674 struct function_table_entry *entry_p;
1676 int min = (entry_p->required_args > 0
1677 ? entry_p->required_args
1678 : -entry_p->required_args);
1680 if (argc < min)
1681 fatal (reading_file,
1682 _("Insufficient number of arguments (%d) to function `%s'"),
1683 argc, entry_p->name);
1685 if (!entry_p->func_ptr)
1686 fatal (reading_file, _("Unimplemented on this platform: function `%s'"),
1687 entry_p->name);
1689 return entry_p->func_ptr (o, argv, entry_p->name);
1692 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1693 opening ( or { and is not null-terminated. If a function invocation
1694 is found, expand it into the buffer at *OP, updating *OP, incrementing
1695 *STRINGP past the reference and returning nonzero. If not, return zero. */
1698 handle_function (op, stringp)
1699 char **op;
1700 char **stringp;
1702 const struct function_table_entry *entry_p;
1703 char openparen = (*stringp)[0];
1704 char closeparen = openparen == '(' ? ')' : '}';
1705 char *beg = *stringp + 1;
1706 char *endref;
1707 int count = 0;
1708 char *argbeg;
1709 register char *p;
1710 char **argv, **argvp;
1711 int nargs;
1713 entry_p = lookup_function (function_table, beg);
1715 if (!entry_p)
1716 return 0;
1718 /* We have found a call to a builtin function. Find the end of the
1719 arguments, and do the function. */
1721 endref = beg + entry_p->len;
1723 /* Space after function name isn't part of the args. */
1724 p = next_token (endref);
1725 argbeg = p;
1727 /* Find the end of the function invocation, counting nested use of
1728 whichever kind of parens we use. Since we're looking, count commas
1729 to get a rough estimate of how many arguments we might have. The
1730 count might be high, but it'll never be low. */
1732 for (nargs=1; *p != '\0'; ++p)
1733 if (*p == ',')
1734 ++nargs;
1735 else if (*p == openparen)
1736 ++count;
1737 else if (*p == closeparen && --count < 0)
1738 break;
1740 if (count >= 0)
1741 fatal (reading_file,
1742 _("unterminated call to function `%s': missing `%c'"),
1743 entry_p->name, closeparen);
1745 /* Get some memory to store the arg pointers. */
1746 argvp = argv = (char **) alloca (sizeof(char *) * (nargs + 2));
1748 /* Chop the string into arguments, then store the end pointer and a nul.
1749 If REQUIRED_ARGS is positive, as soon as we hit that many assume the
1750 rest of the string is part of the last argument. */
1751 *argvp = argbeg;
1752 nargs = 1;
1753 while (entry_p->required_args < 0 || nargs < entry_p->required_args)
1755 char *next = find_next_argument (openparen, closeparen, *argvp, p);
1757 if (!next)
1758 break;
1760 *(++argvp) = next+1;
1761 ++nargs;
1764 *(++argvp) = p+1;
1765 *(++argvp) = 0;
1767 /* If we should expand, do it. */
1768 if (entry_p->expand_args)
1770 for (argvp=argv; argvp[1] != 0; ++argvp)
1771 *argvp = expand_argument (*argvp, argvp[1]-1);
1773 /* end pointer doesn't make sense for expanded stuff. */
1774 *argvp = 0;
1777 /* Finally! Run the function... */
1778 *op = expand_builtin_function (*op, nargs, argv, entry_p);
1780 /* If we allocated memory for the expanded args, free it again. */
1781 if (entry_p->expand_args)
1782 for (argvp=argv; *argvp != 0; ++argvp)
1783 free (*argvp);
1785 *stringp = p;
1787 return 1;
1791 /* User-defined functions. Expand the first argument as either a builtin
1792 function or a make variable, in the context of the rest of the arguments
1793 assigned to $1, $2, ... $N. $0 is the name of the function. */
1795 static char *
1796 func_call (o, argv, funcname)
1797 char *o;
1798 char **argv;
1799 const char *funcname;
1801 char *fname;
1802 int flen;
1803 char *body;
1804 int i;
1805 const struct function_table_entry *entry_p;
1807 /* Calling nothing is a no-op. */
1808 if (*argv[0] == '\0')
1809 return o;
1811 /* There is no way to define a variable with a space in the name, so strip
1812 trailing whitespace as a favor to the user. */
1814 flen = strlen (argv[0]);
1815 fname = argv[0] + flen - 1;
1816 while (isspace ((unsigned char)*fname))
1817 --fname;
1818 fname[1] = '\0';
1820 flen = fname - argv[0] + 1;
1821 fname = argv[0];
1823 /* Are we invoking a builtin function? */
1825 entry_p = lookup_function (function_table, fname);
1827 if (entry_p)
1829 for (i=0; argv[i+1]; ++i)
1832 return expand_builtin_function (o, i, argv + 1, entry_p);
1835 /* No, so the first argument is the name of a variable to be expanded and
1836 interpreted as a function. Create the variable reference. */
1837 body = alloca (flen + 4);
1838 body[0]='$';
1839 body[1]='(';
1840 strcpy (body + 2, fname);
1841 body[flen+2]=')';
1842 body[flen+3]= '\0';
1844 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
1846 push_new_variable_scope ();
1848 for (i=0; *argv; ++i, ++argv)
1850 char num[11];
1852 sprintf (num, "%d", i);
1853 define_variable (num, strlen (num), *argv, o_automatic, 0);
1856 /* Expand the body in the context of the arguments, adding the result to
1857 the variable buffer. */
1859 o = variable_expand_string (o, body, flen+3);
1861 pop_variable_scope ();
1863 return o + strlen(o);