.
[make.git] / function.c
blob6771fa845dff6ba78f4cb54b2307411f35f328fd
1 /* Variable function expansion for GNU Make.
2 Copyright (C) 1988, 89, 91, 92, 93, 94, 95, 96 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, 675 Mass Ave, Cambridge, MA 02139, USA. */
19 #include "make.h"
20 #include "filedef.h"
21 #include "variable.h"
22 #include "dep.h"
23 #include "job.h"
24 #include "commands.h"
26 #ifdef __MSDOS__
27 #include <process.h>
28 #include <fcntl.h>
29 #endif
30 #ifdef _AMIGA
31 #include "amiga.h"
32 #endif
33 #ifdef WIN32
34 #include <windows.h>
35 #include <io.h>
36 #include "sub_proc.h"
37 #endif
39 static char *string_glob PARAMS ((char *line));
41 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
42 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
43 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
44 nonzero, substitutions are done only on matches which are complete
45 whitespace-delimited words. If SUFFIX_ONLY is nonzero, substitutions are
46 done only at the ends of whitespace-delimited words. */
48 char *
49 subst_expand (o, text, subst, replace, slen, rlen, by_word, suffix_only)
50 char *o;
51 char *text;
52 char *subst, *replace;
53 unsigned int slen, rlen;
54 int by_word, suffix_only;
56 register char *t = text;
57 register char *p;
59 if (slen == 0 && !by_word && !suffix_only)
61 /* The first occurrence of "" in any string is its end. */
62 o = variable_buffer_output (o, t, strlen (t));
63 if (rlen > 0)
64 o = variable_buffer_output (o, replace, rlen);
65 return o;
70 if ((by_word | suffix_only) && slen == 0)
71 /* When matching by words, the empty string should match
72 the end of each word, rather than the end of the whole text. */
73 p = end_of_token (next_token (t));
74 else
76 p = sindex (t, 0, subst, slen);
77 if (p == 0)
79 /* No more matches. Output everything left on the end. */
80 o = variable_buffer_output (o, t, strlen (t));
81 return o;
85 /* Output everything before this occurrence of the string to replace. */
86 if (p > t)
87 o = variable_buffer_output (o, t, p - t);
89 /* If we're substituting only by fully matched words,
90 or only at the ends of words, check that this case qualifies. */
91 if ((by_word
92 && ((p > t && !isblank (p[-1]))
93 || (p[slen] != '\0' && !isblank (p[slen]))))
94 || (suffix_only
95 && (p[slen] != '\0' && !isblank (p[slen]))))
96 /* Struck out. Output the rest of the string that is
97 no longer to be replaced. */
98 o = variable_buffer_output (o, subst, slen);
99 else if (rlen > 0)
100 /* Output the replacement string. */
101 o = variable_buffer_output (o, replace, rlen);
103 /* Advance T past the string to be replaced. */
104 t = p + slen;
105 } while (*t != '\0');
107 return o;
111 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
112 and replacing strings matching PATTERN with REPLACE.
113 If PATTERN_PERCENT is not nil, PATTERN has already been
114 run through find_percent, and PATTERN_PERCENT is the result.
115 If REPLACE_PERCENT is not nil, REPLACE has already been
116 run through find_percent, and REPLACE_PERCENT is the result. */
118 char *
119 patsubst_expand (o, text, pattern, replace, pattern_percent, replace_percent)
120 char *o;
121 char *text;
122 register char *pattern, *replace;
123 register char *pattern_percent, *replace_percent;
125 unsigned int pattern_prepercent_len, pattern_postpercent_len;
126 unsigned int replace_prepercent_len, replace_postpercent_len;
127 char *t;
128 unsigned int len;
129 int doneany = 0;
131 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
132 will be collapsed before we call subst_expand if PATTERN has no %. */
133 if (replace_percent == 0)
134 replace_percent = find_percent (replace);
135 if (replace_percent != 0)
137 /* Record the length of REPLACE before and after the % so
138 we don't have to compute these lengths more than once. */
139 replace_prepercent_len = replace_percent - replace;
140 replace_postpercent_len = strlen (replace_percent + 1);
142 else
143 /* We store the length of the replacement
144 so we only need to compute it once. */
145 replace_prepercent_len = strlen (replace);
147 if (pattern_percent == 0)
148 pattern_percent = find_percent (pattern);
149 if (pattern_percent == 0)
150 /* With no % in the pattern, this is just a simple substitution. */
151 return subst_expand (o, text, pattern, replace,
152 strlen (pattern), strlen (replace), 1, 0);
154 /* Record the length of PATTERN before and after the %
155 so we don't have to compute it more than once. */
156 pattern_prepercent_len = pattern_percent - pattern;
157 pattern_postpercent_len = strlen (pattern_percent + 1);
159 while ((t = find_next_token (&text, &len)) != 0)
161 int fail = 0;
163 /* Is it big enough to match? */
164 if (len < pattern_prepercent_len + pattern_postpercent_len)
165 fail = 1;
167 /* Does the prefix match? */
168 if (!fail && pattern_prepercent_len > 0
169 && (*t != *pattern
170 || t[pattern_prepercent_len - 1] != pattern_percent[-1]
171 || strncmp (t + 1, pattern + 1, pattern_prepercent_len - 1)))
172 fail = 1;
174 /* Does the suffix match? */
175 if (!fail && pattern_postpercent_len > 0
176 && (t[len - 1] != pattern_percent[pattern_postpercent_len]
177 || t[len - pattern_postpercent_len] != pattern_percent[1]
178 || strncmp (&t[len - pattern_postpercent_len],
179 &pattern_percent[1], pattern_postpercent_len - 1)))
180 fail = 1;
182 if (fail)
183 /* It didn't match. Output the string. */
184 o = variable_buffer_output (o, t, len);
185 else
187 /* It matched. Output the replacement. */
189 /* Output the part of the replacement before the %. */
190 o = variable_buffer_output (o, replace, replace_prepercent_len);
192 if (replace_percent != 0)
194 /* Output the part of the matched string that
195 matched the % in the pattern. */
196 o = variable_buffer_output (o, t + pattern_prepercent_len,
197 len - (pattern_prepercent_len
198 + pattern_postpercent_len));
199 /* Output the part of the replacement after the %. */
200 o = variable_buffer_output (o, replace_percent + 1,
201 replace_postpercent_len);
205 /* Output a space, but not if the replacement is "". */
206 if (fail || replace_prepercent_len > 0
207 || (replace_percent != 0 && len + replace_postpercent_len > 0))
209 o = variable_buffer_output (o, " ", 1);
210 doneany = 1;
213 if (doneany)
214 /* Kill the last space. */
215 --o;
217 return o;
220 /* Handle variable-expansion-time functions such as $(dir foo/bar) ==> foo/ */
222 /* These enumeration constants distinguish the
223 various expansion-time built-in functions. */
225 enum function
227 function_subst,
228 function_addsuffix,
229 function_addprefix,
230 function_dir,
231 function_notdir,
232 function_suffix,
233 function_basename,
234 function_wildcard,
235 function_firstword,
236 function_word,
237 function_words,
238 function_findstring,
239 function_strip,
240 function_join,
241 function_patsubst,
242 function_filter,
243 function_filter_out,
244 function_foreach,
245 function_sort,
246 function_origin,
247 function_shell,
248 function_invalid
251 /* Greater than the length of any function name. */
252 #define MAXFUNCTIONLEN 11
254 /* The function names and lengths of names, for looking them up. */
256 static struct
258 char *name;
259 unsigned int len;
260 enum function function;
261 } function_table[] =
263 { "subst", 5, function_subst },
264 { "addsuffix", 9, function_addsuffix },
265 { "addprefix", 9, function_addprefix },
266 { "dir", 3, function_dir },
267 { "notdir", 6, function_notdir },
268 { "suffix", 6, function_suffix },
269 { "basename", 8, function_basename },
270 { "wildcard", 8, function_wildcard },
271 { "firstword", 9, function_firstword },
272 { "word", 4, function_word },
273 { "words", 5, function_words },
274 { "findstring", 10, function_findstring },
275 { "strip", 5, function_strip },
276 { "join", 4, function_join },
277 { "patsubst", 8, function_patsubst },
278 { "filter", 6, function_filter },
279 { "filter-out", 10, function_filter_out },
280 { "foreach", 7, function_foreach },
281 { "sort", 4, function_sort },
282 { "origin", 6, function_origin },
283 { "shell", 5, function_shell },
284 { 0, 0, function_invalid }
287 /* Return 1 if PATTERN matches WORD, 0 if not. */
290 pattern_matches (pattern, percent, word)
291 register char *pattern, *percent, *word;
293 unsigned int sfxlen, wordlen;
295 if (percent == 0)
297 unsigned int len = strlen (pattern) + 1;
298 char *new = (char *) alloca (len);
299 bcopy (pattern, new, len);
300 pattern = new;
301 percent = find_percent (pattern);
302 if (percent == 0)
303 return streq (pattern, word);
306 sfxlen = strlen (percent + 1);
307 wordlen = strlen (word);
309 if (wordlen < (percent - pattern) + sfxlen
310 || strncmp (pattern, word, percent - pattern))
311 return 0;
313 return !strcmp (percent + 1, word + (wordlen - sfxlen));
316 int shell_function_pid = 0, shell_function_completed;
318 /* Perform the function specified by FUNCTION on the text at TEXT.
319 END is points to the end of the argument text (exclusive).
320 The output is written into VARIABLE_BUFFER starting at O. */
322 /* Note this absorbs a semicolon and is safe to use in conditionals. */
323 #define BADARGS(func) \
324 if (reading_filename != 0) \
325 makefile_fatal (reading_filename, *reading_lineno_ptr, \
326 "insufficient arguments to function `%s'", \
327 func); \
328 else \
329 fatal ("insufficient arguments to function `%s'", func)
331 static char *
332 expand_function (o, function, text, end)
333 char *o;
334 enum function function;
335 char *text;
336 char *end;
338 char *p, *p2, *p3;
339 unsigned int i, len;
340 int doneany = 0;
341 int count;
342 char endparen = *end, startparen = *end == ')' ? '(' : '{';
344 switch (function)
346 default:
347 abort ();
348 break;
350 #ifndef VMS /* not supported for vms yet */
351 case function_shell:
353 #ifdef WIN32
354 SECURITY_ATTRIBUTES saAttr;
355 HANDLE hIn;
356 HANDLE hErr;
357 HANDLE hChildOutRd;
358 HANDLE hChildOutWr;
359 HANDLE hProcess;
360 #endif
361 char **argv;
362 char *error_prefix;
363 #ifndef _AMIGA
364 char **envp;
365 int pipedes[2];
366 int pid;
367 #endif
369 /* Expand the command line. */
370 text = expand_argument (text, end);
372 /* Construct the argument list. */
373 argv = construct_command_argv (text,
374 (char **) NULL, (struct file *) 0);
375 if (argv == 0)
376 break;
378 #ifndef _AMIGA
379 /* Using a target environment for `shell' loses in cases like:
380 export var = $(shell echo foobie)
381 because target_environment hits a loop trying to expand $(var)
382 to put it in the environment. This is even more confusing when
383 var was not explicitly exported, but just appeared in the
384 calling environment. */
385 #if 1
386 envp = environ;
387 #else
388 /* Construct the environment. */
389 envp = target_environment ((struct file *) 0);
390 #endif
391 #endif /* Not Amiga. */
393 /* For error messages. */
394 if (reading_filename != 0)
396 error_prefix = (char *) alloca (strlen (reading_filename) + 100);
397 sprintf (error_prefix,
398 "%s:%u: ", reading_filename, *reading_lineno_ptr);
400 else
401 error_prefix = "";
403 #if !defined(__MSDOS__) && !defined(_AMIGA)
404 # ifdef WIN32
405 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
406 saAttr.bInheritHandle = TRUE;
407 saAttr.lpSecurityDescriptor = NULL;
409 if (DuplicateHandle(GetCurrentProcess(),
410 GetStdHandle(STD_INPUT_HANDLE),
411 GetCurrentProcess(),
412 &hIn,
414 TRUE,
415 DUPLICATE_SAME_ACCESS) == FALSE) {
416 fatal("create_child_process: DuplicateHandle(In) failed (e=%d)\n",
417 GetLastError());
419 if (DuplicateHandle(GetCurrentProcess(),
420 GetStdHandle(STD_ERROR_HANDLE),
421 GetCurrentProcess(),
422 &hErr,
424 TRUE,
425 DUPLICATE_SAME_ACCESS) == FALSE) {
426 fatal("create_child_process: DuplicateHandle(Err) failed (e=%d)\n",
427 GetLastError());
430 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
431 fatal("CreatePipe() failed (e=%d)\n", GetLastError());
433 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
435 if (!hProcess)
436 fatal("expand_function: process_init_fd() failed\n");
437 else
438 process_register(hProcess);
440 /* make sure that CreateProcess() has Path it needs */
441 sync_Path_environment();
443 if (!process_begin(hProcess, argv, envp, argv[0], NULL))
444 pid = (int) hProcess;
445 else
446 fatal("expand_function: unable to launch process (e=%d)\n",
447 process_last_err(hProcess));
449 /* set up to read data from child */
450 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
452 /* this will be closed almost right away */
453 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
454 # else /* WIN32 */
455 if (pipe (pipedes) < 0)
457 perror_with_name (error_prefix, "pipe");
458 break;
461 pid = vfork ();
462 if (pid < 0)
463 perror_with_name (error_prefix, "fork");
464 else if (pid == 0)
465 child_execute_job (0, pipedes[1], argv, envp);
466 else
467 # endif /* WIN32 */
469 /* We are the parent. */
471 char *buffer;
472 unsigned int maxlen;
473 int cc;
475 /* Free the storage only the child needed. */
476 free (argv[0]);
477 free ((char *) argv);
478 #if 0
479 for (i = 0; envp[i] != 0; ++i)
480 free (envp[i]);
481 free ((char *) envp);
482 #endif
484 /* Record the PID for reap_children. */
485 shell_function_pid = pid;
486 shell_function_completed = 0;
489 /* Set up and read from the pipe. */
491 maxlen = 200;
492 buffer = (char *) xmalloc (maxlen + 1);
494 /* Close the write side of the pipe. */
495 (void) close (pipedes[1]);
497 /* Read from the pipe until it gets EOF. */
498 i = 0;
501 if (i == maxlen)
503 maxlen += 512;
504 buffer = (char *) xrealloc (buffer, maxlen + 1);
507 errno = 0;
508 cc = read (pipedes[0], &buffer[i], maxlen - i);
509 if (cc > 0)
510 i += cc;
512 #ifdef EINTR
513 while (cc > 0 || errno == EINTR);
514 #else
515 while (cc > 0);
516 #endif
518 /* Close the read side of the pipe. */
519 (void) close (pipedes[0]);
521 /* Loop until child_handler sets shell_function_completed
522 to the status of our child shell. */
523 while (shell_function_completed == 0)
524 reap_children (1, 0);
526 shell_function_pid = 0;
528 /* The child_handler function will set shell_function_completed
529 to 1 when the child dies normally, or to -1 if it
530 dies with status 127, which is most likely an exec fail. */
532 if (shell_function_completed == -1)
534 /* This most likely means that the execvp failed,
535 so we should just write out the error message
536 that came in over the pipe from the child. */
537 fputs (buffer, stderr);
538 fflush (stderr);
540 else
542 /* The child finished normally. Replace all
543 newlines in its output with spaces, and put
544 that in the variable output buffer. */
545 if (i > 0)
547 if (buffer[i - 1] == '\n')
548 buffer[--i] = '\0';
549 else
550 buffer[i] = '\0';
551 p = buffer;
552 while ((p = index (p, '\n')) != 0)
553 *p++ = ' ';
554 o = variable_buffer_output (o, buffer, i);
558 free (buffer);
560 #else /* MSDOS or Amiga */
561 #ifndef _AMIGA
563 /* MS-DOS can't do fork, but it can do spawn. However, this
564 means that we don't have an opportunity to reopen stdout to
565 trap it. Thus, we save our own stdout onto a new descriptor
566 and dup a temp file's descriptor onto our stdout temporarily.
567 After we spawn the shell program, we dup our own stdout back
568 to the stdout descriptor. The buffer reading is the same as
569 above, except that we're now reading from a file. */
571 int save_stdout;
572 int child_stdout;
573 char tmp_output[FILENAME_MAX];
574 FILE *child_stream;
575 unsigned int maxlen = 200;
576 int cc;
577 char *buffer;
579 strcpy (tmp_output, "shXXXXXX");
580 mktemp (tmp_output);
581 child_stdout = open (tmp_output,
582 O_WRONLY|O_CREAT|O_TRUNC|O_TEXT, 0644);
583 save_stdout = dup (1);
584 dup2 (child_stdout, 1);
585 spawnvp (P_WAIT, argv[0], argv);
586 dup2 (save_stdout, 1);
587 close (child_stdout);
588 close (save_stdout);
590 child_stdout = open (tmp_output, O_RDONLY|O_TEXT, 0644);
592 buffer = xmalloc (maxlen);
593 i = 0;
596 if (i == maxlen)
598 maxlen += 512;
599 buffer = (char *) xrealloc (buffer, maxlen + 1);
602 cc = read (child_stdout, &buffer[i], maxlen - i);
603 if (cc > 0)
604 i += cc;
605 } while (cc > 0);
607 close (child_stdout);
608 unlink (tmp_output);
610 if (i > 0)
612 if (buffer[i - 1] == '\n')
613 buffer[--i] = '\0';
614 else
615 buffer[i] = '\0';
616 p = buffer;
617 while ((p = index (p, '\n')) != 0)
618 *p++ = ' ';
619 o = variable_buffer_output (o, buffer, i);
621 free (buffer);
623 #else /* Amiga */
625 /* Amiga can't fork nor spawn, but I can start a program with
626 redirection of my choice. The rest is the same as above. */
627 #include <dos/dos.h>
628 #include <proto/dos.h>
630 BPTR child_stdout;
631 char tmp_output[FILENAME_MAX];
632 unsigned int maxlen = 200;
633 int cc;
634 char * buffer, * ptr;
635 char ** aptr;
636 int len = 0;
638 strcpy (tmp_output, "t:MakeshXXXXXXXX");
639 mktemp (tmp_output);
640 child_stdout = Open (tmp_output, MODE_NEWFILE);
642 for (aptr=argv; *aptr; aptr++)
644 len += strlen (*aptr) + 1;
647 buffer = xmalloc (len + 1);
648 ptr = buffer;
650 for (aptr=argv; *aptr; aptr++)
652 strcpy (ptr, *aptr);
653 ptr += strlen (ptr) + 1;
654 *ptr ++ = ' ';
655 *ptr = 0;
658 ptr[-1] = '\n';
660 Execute (buffer, NULL, child_stdout);
661 free (buffer);
663 Close (child_stdout);
665 child_stdout = Open (tmp_output, MODE_OLDFILE);
667 buffer = xmalloc (maxlen);
668 i = 0;
671 if (i == maxlen)
673 maxlen += 512;
674 buffer = (char *) xrealloc (buffer, maxlen + 1);
677 cc = Read (child_stdout, &buffer[i], maxlen - i);
678 if (cc > 0)
679 i += cc;
680 } while (cc > 0);
682 Close (child_stdout);
683 DeleteFile (tmp_output);
685 if (i > 0)
687 if (buffer[i - 1] == '\n')
688 buffer[--i] = '\0';
689 else
690 buffer[i] = '\0';
691 p = buffer;
692 while ((p = index (p, '\n')) != 0)
693 *p++ = ' ';
694 o = variable_buffer_output (o, buffer, i);
696 free (buffer);
698 #endif /* Not Amiga. */
699 #endif /* MSDOS or Amiga. */
701 free (text);
702 break;
704 #endif /* !VMS */
706 case function_origin:
707 /* Expand the argument. */
708 text = expand_argument (text, end);
711 register struct variable *v = lookup_variable (text, strlen (text));
712 if (v == 0)
713 o = variable_buffer_output (o, "undefined", 9);
714 else
715 switch (v->origin)
717 default:
718 case o_invalid:
719 abort ();
720 break;
721 case o_default:
722 o = variable_buffer_output (o, "default", 7);
723 break;
724 case o_env:
725 o = variable_buffer_output (o, "environment", 11);
726 break;
727 case o_file:
728 o = variable_buffer_output (o, "file", 4);
729 break;
730 case o_env_override:
731 o = variable_buffer_output (o, "environment override", 20);
732 break;
733 case o_command:
734 o = variable_buffer_output (o, "command line", 12);
735 break;
736 case o_override:
737 o = variable_buffer_output (o, "override", 8);
738 break;
739 case o_automatic:
740 o = variable_buffer_output (o, "automatic", 9);
741 break;
745 free (text);
746 break;
748 case function_sort:
749 /* Expand the argument. */
750 text = expand_argument (text, end);
753 char **words = (char **) xmalloc (10 * sizeof (char *));
754 unsigned int nwords = 10;
755 register unsigned int wordi = 0;
756 char *t;
758 /* Chop TEXT into words and put them in WORDS. */
759 t = text;
760 while ((p = find_next_token (&t, &len)) != 0)
762 if (wordi >= nwords - 1)
764 nwords *= 2;
765 words = (char **) xrealloc ((char *) words,
766 nwords * sizeof (char *));
768 words[wordi++] = savestring (p, len);
771 if (wordi > 0)
773 /* Now sort the list of words. */
774 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
776 /* Now write the sorted list. */
777 for (i = 0; i < wordi; ++i)
779 len = strlen (words[i]);
780 if (i == wordi - 1 || strlen (words[i + 1]) != len
781 || strcmp (words[i], words[i + 1]))
783 o = variable_buffer_output (o, words[i], len);
784 o = variable_buffer_output (o, " ", 1);
786 free (words[i]);
788 /* Kill the last space. */
789 --o;
792 free ((char *) words);
795 free (text);
796 break;
798 case function_foreach:
800 /* Get three comma-separated arguments but
801 expand only the first two. */
802 char *var, *list;
803 register struct variable *v;
805 count = 0;
806 for (p = text; p < end; ++p)
808 if (*p == startparen)
809 ++count;
810 else if (*p == endparen)
811 --count;
812 else if (*p == ',' && count <= 0)
813 break;
815 if (p == end)
816 BADARGS ("foreach");
817 var = expand_argument (text, p);
819 p2 = p + 1;
820 count = 0;
821 for (p = p2; p < end; ++p)
823 if (*p == startparen)
824 ++count;
825 else if (*p == endparen)
826 --count;
827 else if (*p == ',' && count <= 0)
828 break;
830 if (p == end)
831 BADARGS ("foreach");
832 list = expand_argument (p2, p);
834 ++p;
835 text = savestring (p, end - p);
837 push_new_variable_scope ();
838 v = define_variable (var, strlen (var), "", o_automatic, 0);
839 p3 = list;
840 while ((p = find_next_token (&p3, &len)) != 0)
842 char *result;
843 char save = p[len];
844 p[len] = '\0';
845 v->value = p;
846 result = allocated_variable_expand (text);
847 p[len] = save;
849 o = variable_buffer_output (o, result, strlen (result));
850 o = variable_buffer_output (o, " ", 1);
851 doneany = 1;
852 free (result);
854 if (doneany)
855 /* Kill the last space. */
856 --o;
858 pop_variable_scope ();
860 free (var);
861 free (list);
862 free (text);
864 break;
866 case function_filter:
867 case function_filter_out:
869 struct word
871 struct word *next;
872 char *word;
873 int matched;
874 } *words, *wordtail, *wp;
876 /* Get two comma-separated arguments and expand each one. */
877 count = 0;
878 for (p = text; p < end; ++p)
880 if (*p == startparen)
881 ++count;
882 else if (*p == endparen)
883 --count;
884 else if (*p == ',' && count <= 0)
885 break;
887 if (p == end)
888 BADARGS (function == function_filter ? "filter" : "filter-out");
889 p2 = expand_argument (text, p);
891 text = expand_argument (p + 1, end);
893 /* Chop TEXT up into words and then run each pattern through. */
894 words = wordtail = 0;
895 p3 = text;
896 while ((p = find_next_token (&p3, &len)) != 0)
898 struct word *w = (struct word *) alloca (sizeof (struct word));
899 if (words == 0)
900 words = w;
901 else
902 wordtail->next = w;
903 wordtail = w;
905 if (*p3 != '\0')
906 ++p3;
907 p[len] = '\0';
908 w->word = p;
909 w->matched = 0;
912 if (words != 0)
914 wordtail->next = 0;
916 /* Run each pattern through the words, killing words. */
917 p3 = p2;
918 while ((p = find_next_token (&p3, &len)) != 0)
920 char *percent;
921 char save = p[len];
922 p[len] = '\0';
924 percent = find_percent (p);
925 for (wp = words; wp != 0; wp = wp->next)
926 wp->matched |= (percent == 0 ? streq (p, wp->word)
927 : pattern_matches (p, percent, wp->word));
929 p[len] = save;
932 /* Output the words that matched (or didn't, for filter-out). */
933 for (wp = words; wp != 0; wp = wp->next)
934 if (function == function_filter ? wp->matched : !wp->matched)
936 o = variable_buffer_output (o, wp->word, strlen (wp->word));
937 o = variable_buffer_output (o, " ", 1);
938 doneany = 1;
940 if (doneany)
941 /* Kill the last space. */
942 --o;
945 free (p2);
946 free (text);
948 break;
950 case function_patsubst:
951 /* Get three comma-separated arguments and expand each one. */
952 count = 0;
953 for (p = text; p < end; ++p)
955 if (*p == startparen)
956 ++count;
957 else if (*p == endparen)
958 --count;
959 else if (*p == ',' && count <= 0)
960 break;
962 if (p == end)
963 BADARGS ("patsubst");
965 p2 = p;
966 count = 0;
967 for (++p; p < end; ++p)
969 if (*p == startparen)
970 ++count;
971 else if (*p == endparen)
972 --count;
973 else if (*p == ',' && count <= 0)
974 break;
976 if (p == end)
977 BADARGS ("patsubst");
979 text = expand_argument (text, p2);
980 p3 = expand_argument (p2 + 1, p);
981 p2 = expand_argument (p + 1, end);
983 o = patsubst_expand (o, p2, text, p3, (char *) 0, (char *) 0);
985 free (text);
986 free (p3);
987 free (p2);
988 break;
990 case function_join:
991 /* Get two comma-separated arguments and expand each one. */
992 count = 0;
993 for (p = text; p < end; ++p)
995 if (*p == startparen)
996 ++count;
997 else if (*p == endparen)
998 --count;
999 else if (*p == ',' && count <= 0)
1000 break;
1002 if (p == end)
1003 BADARGS ("join");
1004 text = expand_argument (text, p);
1006 p = expand_argument (p + 1, end);
1009 /* Write each word of the first argument directly followed
1010 by the corresponding word of the second argument.
1011 If the two arguments have a different number of words,
1012 the excess words are just output separated by blanks. */
1013 register char *tp, *pp;
1014 p2 = text;
1015 p3 = p;
1018 unsigned int tlen, plen;
1020 tp = find_next_token (&p2, &tlen);
1021 if (tp != 0)
1022 o = variable_buffer_output (o, tp, tlen);
1024 pp = find_next_token (&p3, &plen);
1025 if (pp != 0)
1026 o = variable_buffer_output (o, pp, plen);
1028 if (tp != 0 || pp != 0)
1030 o = variable_buffer_output (o, " ", 1);
1031 doneany = 1;
1034 while (tp != 0 || pp != 0);
1035 if (doneany)
1036 /* Kill the last blank. */
1037 --o;
1040 free (text);
1041 free (p);
1042 break;
1044 case function_strip:
1045 /* Expand the argument. */
1046 text = expand_argument (text, end);
1048 p2 = text;
1049 while ((p = find_next_token (&p2, &i)) != 0)
1051 o = variable_buffer_output (o, p, i);
1052 o = variable_buffer_output (o, " ", 1);
1053 doneany = 1;
1055 if (doneany)
1056 /* Kill the last space. */
1057 --o;
1059 free (text);
1060 break;
1062 case function_wildcard:
1063 text = expand_argument (text, end);
1065 #ifdef _AMIGA
1066 o = wildcard_expansion (text, o);
1067 #else
1068 p = string_glob (text);
1069 o = variable_buffer_output (o, p, strlen (p));
1070 #endif
1072 free (text);
1073 break;
1075 case function_subst:
1076 /* Get three comma-separated arguments and expand each one. */
1077 count = 0;
1078 for (p = text; p < end; ++p)
1080 if (*p == startparen)
1081 ++count;
1082 else if (*p == endparen)
1083 --count;
1084 else if (*p == ',' && count <= 0)
1085 break;
1087 if (p == end)
1088 BADARGS ("subst");
1090 p2 = p;
1091 count = 0;
1092 for (++p; p < end; ++p)
1094 if (*p == startparen)
1095 ++count;
1096 else if (*p == endparen)
1097 --count;
1098 else if (*p == ',' && count <= 0)
1099 break;
1101 if (p == end)
1102 BADARGS ("subst");
1104 text = expand_argument (text, p2);
1105 p3 = expand_argument (p2 + 1, p);
1106 p2 = expand_argument (p + 1, end);
1108 o = subst_expand (o, p2, text, p3, strlen (text), strlen (p3), 0, 0);
1110 free (text);
1111 free (p3);
1112 free (p2);
1113 break;
1115 case function_firstword:
1116 /* Expand the argument. */
1117 text = expand_argument (text, end);
1119 /* Find the first word in TEXT. */
1120 p2 = text;
1121 p = find_next_token (&p2, &i);
1122 if (p != 0)
1123 o = variable_buffer_output (o, p, i);
1125 free (text);
1126 break;
1128 case function_word:
1129 /* Get two comma-separated arguments and expand each one. */
1130 count = 0;
1131 for (p = text; p < end; ++p)
1133 if (*p == startparen)
1134 ++count;
1135 else if (*p == endparen)
1136 --count;
1137 else if (*p == ',' && count <= 0)
1138 break;
1140 if (p == end)
1141 BADARGS ("word");
1142 text = expand_argument (text, p);
1144 p3 = expand_argument (p + 1, end);
1146 /* Check the first argument. */
1147 for (p2 = text; *p2 != '\0'; ++p2)
1148 if (*p2 < '0' || *p2 > '9')
1150 if (reading_filename != 0)
1151 makefile_fatal (reading_filename, *reading_lineno_ptr,
1152 "non-numeric first argument to `word' function");
1153 else
1154 fatal ("non-numeric first argument to `word' function");
1157 i = (unsigned int) atoi (text);
1158 if (i == 0)
1160 if (reading_filename != 0)
1161 makefile_fatal (reading_filename, *reading_lineno_ptr,
1162 "the `word' function takes a one-origin \
1163 index argument");
1164 else
1165 fatal ("the `word' function takes a one-origin index argument");
1168 p2 = p3;
1169 while ((p = find_next_token (&p2, &len)) != 0)
1170 if (--i == 0)
1171 break;
1172 if (i == 0)
1173 o = variable_buffer_output (o, p, len);
1175 free (text);
1176 free (p3);
1177 break;
1179 case function_words:
1180 /* Expand the argument. */
1181 text = expand_argument (text, end);
1183 i = 0;
1184 p2 = text;
1185 while (find_next_token (&p2, (unsigned int *) 0) != 0)
1186 ++i;
1189 char buf[20];
1190 sprintf (buf, "%d", i);
1191 o = variable_buffer_output (o, buf, strlen (buf));
1194 free (text);
1195 break;
1197 case function_findstring:
1198 /* Get two comma-separated arguments and expand each one. */
1199 count = 0;
1200 for (p = text; p < end; ++p)
1202 if (*p == startparen)
1203 ++count;
1204 else if (*p == endparen)
1205 --count;
1206 else if (*p == ',' && count <= 0)
1207 break;
1209 if (p == end)
1210 BADARGS ("findstring");
1211 text = expand_argument (text, p);
1213 p = expand_argument (p + 1, end);
1215 /* Find the first occurrence of the first string in the second. */
1216 i = strlen (text);
1217 if (sindex (p, 0, text, i) != 0)
1218 o = variable_buffer_output (o, text, i);
1220 free (p);
1221 free (text);
1222 break;
1224 case function_addsuffix:
1225 case function_addprefix:
1226 /* Get two comma-separated arguments and expand each one. */
1227 count = 0;
1228 for (p = text; p < end; ++p)
1230 if (*p == startparen)
1231 ++count;
1232 else if (*p == endparen)
1233 --count;
1234 else if (*p == ',' && count <= 0)
1235 break;
1237 if (p == end)
1238 BADARGS (function == function_addsuffix ? "addsuffix" : "addprefix");
1239 text = expand_argument (text, p);
1240 i = strlen (text);
1242 p2 = expand_argument (p + 1, end);
1244 p3 = p2;
1245 while ((p = find_next_token (&p3, &len)) != 0)
1247 if (function == function_addprefix)
1248 o = variable_buffer_output (o, text, i);
1249 o = variable_buffer_output (o, p, len);
1250 if (function == function_addsuffix)
1251 o = variable_buffer_output (o, text, i);
1252 o = variable_buffer_output (o, " ", 1);
1253 doneany = 1;
1255 if (doneany)
1256 /* Kill last space. */
1257 --o;
1259 free (p2);
1260 free (text);
1261 break;
1263 case function_dir:
1264 case function_basename:
1265 /* Expand the argument. */
1266 text = expand_argument (text, end);
1268 p3 = text;
1269 while ((p2 = find_next_token (&p3, &len)) != 0)
1271 p = p2 + len;
1272 #ifdef VMS
1273 while (p >= p2 && *p != (function == function_dir ? ']' : '.'))
1274 #else
1275 while (p >= p2 && *p != (function == function_dir ? '/' : '.'))
1276 #endif
1277 --p;
1278 if (p >= p2)
1280 if (function == function_dir)
1281 ++p;
1282 o = variable_buffer_output (o, p2, p - p2);
1284 else if (function == function_dir)
1285 #ifdef VMS
1286 o = variable_buffer_output (o, "[]", 2);
1287 #else
1288 #ifndef _AMIGA
1289 o = variable_buffer_output (o, "./", 2);
1290 #else
1291 /* o = o */; /* Just a nop... */
1292 #endif /* AMIGA */
1293 #endif /* !VMS */
1294 else
1295 /* The entire name is the basename. */
1296 o = variable_buffer_output (o, p2, len);
1298 o = variable_buffer_output (o, " ", 1);
1299 doneany = 1;
1301 if (doneany)
1302 /* Kill last space. */
1303 --o;
1305 free (text);
1306 break;
1308 case function_notdir:
1309 case function_suffix:
1310 /* Expand the argument. */
1311 text = expand_argument (text, end);
1313 p3 = text;
1314 while ((p2 = find_next_token (&p3, &len)) != 0)
1316 p = p2 + len;
1317 #ifdef VMS
1318 while (p >= p2 && *p != (function == function_notdir ? ']' : '.'))
1319 #else
1320 while (p >= p2 && *p != (function == function_notdir ? '/' : '.'))
1321 #endif
1322 --p;
1323 if (p >= p2)
1325 if (function == function_notdir)
1326 ++p;
1327 o = variable_buffer_output (o, p, len - (p - p2));
1329 else if (function == function_notdir)
1330 o = variable_buffer_output (o, p2, len);
1332 if (function == function_notdir || p >= p2)
1334 o = variable_buffer_output (o, " ", 1);
1335 doneany = 1;
1338 if (doneany)
1339 /* Kill last space. */
1340 --o;
1342 free (text);
1343 break;
1346 return o;
1349 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1350 opening ( or { and is not null-terminated. If a function invocation
1351 is found, expand it into the buffer at *OP, updating *OP, incrementing
1352 *STRINGP past the reference and returning nonzero. If not, return zero. */
1355 handle_function (op, stringp)
1356 char **op;
1357 char **stringp;
1360 register unsigned int code;
1361 unsigned int maxlen;
1362 char *beg = *stringp + 1;
1363 char *endref;
1365 endref = lindex (beg, beg + MAXFUNCTIONLEN, '\0');
1366 maxlen = endref != 0 ? endref - beg : MAXFUNCTIONLEN;
1368 for (code = 0; function_table[code].name != 0; ++code)
1370 if (maxlen < function_table[code].len)
1371 continue;
1372 endref = beg + function_table[code].len;
1373 if (isblank (*endref)
1374 && !strncmp (function_table[code].name, beg,
1375 function_table[code].len))
1376 break;
1378 if (function_table[code].name != 0)
1380 /* We have found a call to an expansion-time function.
1381 Find the end of the arguments, and do the function. */
1383 char openparen = beg[-1], closeparen = openparen == '(' ? ')' : '}';
1384 int count = 0;
1385 char *argbeg;
1386 register char *p;
1388 /* Space after function name isn't part of the args. */
1389 p = next_token (endref);
1390 argbeg = p;
1392 /* Count nested use of whichever kind of parens we use,
1393 so that nested calls and variable refs work. */
1395 for (; *p != '\0'; ++p)
1397 if (*p == openparen)
1398 ++count;
1399 else if (*p == closeparen && --count < 0)
1400 break;
1403 if (count >= 0)
1405 static const char errmsg[]
1406 = "unterminated call to function `%s': missing `%c'";
1407 if (reading_filename == 0)
1408 fatal (errmsg, function_table[code].name, closeparen);
1409 else
1410 makefile_fatal (reading_filename, *reading_lineno_ptr, errmsg,
1411 function_table[code].name, closeparen);
1414 /* We found the end; expand the function call. */
1416 *op = expand_function (*op, function_table[code].function, argbeg, p);
1417 *stringp = p;
1418 return 1;
1421 return 0;
1424 /* Glob-expand LINE. The returned pointer is
1425 only good until the next call to string_glob. */
1427 static char *
1428 string_glob (line)
1429 char *line;
1431 static char *result = 0;
1432 static unsigned int length;
1433 register struct nameseq *chain;
1434 register unsigned int idx;
1436 chain = multi_glob (parse_file_seq
1437 (&line, '\0', sizeof (struct nameseq),
1438 /* We do not want parse_file_seq to strip `./'s.
1439 That would break examples like:
1440 $(patsubst ./%.c,obj/%.o,$(wildcard ./*.c)). */
1442 sizeof (struct nameseq));
1444 if (result == 0)
1446 length = 100;
1447 result = (char *) xmalloc (100);
1450 idx = 0;
1451 while (chain != 0)
1453 register char *name = chain->name;
1454 unsigned int len = strlen (name);
1456 struct nameseq *next = chain->next;
1457 free ((char *) chain);
1458 chain = next;
1460 /* multi_glob will pass names without globbing metacharacters
1461 through as is, but we want only files that actually exist. */
1462 if (file_exists_p (name))
1464 if (idx + len + 1 > length)
1466 length += (len + 1) * 2;
1467 result = (char *) xrealloc (result, length);
1469 bcopy (name, &result[idx], len);
1470 idx += len;
1471 result[idx++] = ' ';
1474 free (name);
1477 /* Kill the last space and terminate the string. */
1478 if (idx == 0)
1479 result[0] = '\0';
1480 else
1481 result[idx - 1] = '\0';
1483 return result;