Last-minute changed for 3.75.1
[make.git] / function.c
blob125a994fdfab5b6c7db894e368b444c1cdc218da
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 _AMIGA
27 #include "amiga.h"
28 #endif
29 #ifdef WINDOWS32
30 #include <windows.h>
31 #include <io.h>
32 #include "sub_proc.h"
33 #endif
35 static char *string_glob PARAMS ((char *line));
37 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
38 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
39 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
40 nonzero, substitutions are done only on matches which are complete
41 whitespace-delimited words. If SUFFIX_ONLY is nonzero, substitutions are
42 done only at the ends of whitespace-delimited words. */
44 char *
45 subst_expand (o, text, subst, replace, slen, rlen, by_word, suffix_only)
46 char *o;
47 char *text;
48 char *subst, *replace;
49 unsigned int slen, rlen;
50 int by_word, suffix_only;
52 register char *t = text;
53 register char *p;
55 if (slen == 0 && !by_word && !suffix_only)
57 /* The first occurrence of "" in any string is its end. */
58 o = variable_buffer_output (o, t, strlen (t));
59 if (rlen > 0)
60 o = variable_buffer_output (o, replace, rlen);
61 return o;
66 if ((by_word | suffix_only) && slen == 0)
67 /* When matching by words, the empty string should match
68 the end of each word, rather than the end of the whole text. */
69 p = end_of_token (next_token (t));
70 else
72 p = sindex (t, 0, subst, slen);
73 if (p == 0)
75 /* No more matches. Output everything left on the end. */
76 o = variable_buffer_output (o, t, strlen (t));
77 return o;
81 /* Output everything before this occurrence of the string to replace. */
82 if (p > t)
83 o = variable_buffer_output (o, t, p - t);
85 /* If we're substituting only by fully matched words,
86 or only at the ends of words, check that this case qualifies. */
87 if ((by_word
88 && ((p > t && !isblank (p[-1]))
89 || (p[slen] != '\0' && !isblank (p[slen]))))
90 || (suffix_only
91 && (p[slen] != '\0' && !isblank (p[slen]))))
92 /* Struck out. Output the rest of the string that is
93 no longer to be replaced. */
94 o = variable_buffer_output (o, subst, slen);
95 else if (rlen > 0)
96 /* Output the replacement string. */
97 o = variable_buffer_output (o, replace, rlen);
99 /* Advance T past the string to be replaced. */
100 t = p + slen;
101 } while (*t != '\0');
103 return o;
107 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
108 and replacing strings matching PATTERN with REPLACE.
109 If PATTERN_PERCENT is not nil, PATTERN has already been
110 run through find_percent, and PATTERN_PERCENT is the result.
111 If REPLACE_PERCENT is not nil, REPLACE has already been
112 run through find_percent, and REPLACE_PERCENT is the result. */
114 char *
115 patsubst_expand (o, text, pattern, replace, pattern_percent, replace_percent)
116 char *o;
117 char *text;
118 register char *pattern, *replace;
119 register char *pattern_percent, *replace_percent;
121 unsigned int pattern_prepercent_len, pattern_postpercent_len;
122 unsigned int replace_prepercent_len, replace_postpercent_len;
123 char *t;
124 unsigned int len;
125 int doneany = 0;
127 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
128 will be collapsed before we call subst_expand if PATTERN has no %. */
129 if (replace_percent == 0)
130 replace_percent = find_percent (replace);
131 if (replace_percent != 0)
133 /* Record the length of REPLACE before and after the % so
134 we don't have to compute these lengths more than once. */
135 replace_prepercent_len = replace_percent - replace;
136 replace_postpercent_len = strlen (replace_percent + 1);
138 else
139 /* We store the length of the replacement
140 so we only need to compute it once. */
141 replace_prepercent_len = strlen (replace);
143 if (pattern_percent == 0)
144 pattern_percent = find_percent (pattern);
145 if (pattern_percent == 0)
146 /* With no % in the pattern, this is just a simple substitution. */
147 return subst_expand (o, text, pattern, replace,
148 strlen (pattern), strlen (replace), 1, 0);
150 /* Record the length of PATTERN before and after the %
151 so we don't have to compute it more than once. */
152 pattern_prepercent_len = pattern_percent - pattern;
153 pattern_postpercent_len = strlen (pattern_percent + 1);
155 while ((t = find_next_token (&text, &len)) != 0)
157 int fail = 0;
159 /* Is it big enough to match? */
160 if (len < pattern_prepercent_len + pattern_postpercent_len)
161 fail = 1;
163 /* Does the prefix match? */
164 if (!fail && pattern_prepercent_len > 0
165 && (*t != *pattern
166 || t[pattern_prepercent_len - 1] != pattern_percent[-1]
167 || strncmp (t + 1, pattern + 1, pattern_prepercent_len - 1)))
168 fail = 1;
170 /* Does the suffix match? */
171 if (!fail && pattern_postpercent_len > 0
172 && (t[len - 1] != pattern_percent[pattern_postpercent_len]
173 || t[len - pattern_postpercent_len] != pattern_percent[1]
174 || strncmp (&t[len - pattern_postpercent_len],
175 &pattern_percent[1], pattern_postpercent_len - 1)))
176 fail = 1;
178 if (fail)
179 /* It didn't match. Output the string. */
180 o = variable_buffer_output (o, t, len);
181 else
183 /* It matched. Output the replacement. */
185 /* Output the part of the replacement before the %. */
186 o = variable_buffer_output (o, replace, replace_prepercent_len);
188 if (replace_percent != 0)
190 /* Output the part of the matched string that
191 matched the % in the pattern. */
192 o = variable_buffer_output (o, t + pattern_prepercent_len,
193 len - (pattern_prepercent_len
194 + pattern_postpercent_len));
195 /* Output the part of the replacement after the %. */
196 o = variable_buffer_output (o, replace_percent + 1,
197 replace_postpercent_len);
201 /* Output a space, but not if the replacement is "". */
202 if (fail || replace_prepercent_len > 0
203 || (replace_percent != 0 && len + replace_postpercent_len > 0))
205 o = variable_buffer_output (o, " ", 1);
206 doneany = 1;
209 if (doneany)
210 /* Kill the last space. */
211 --o;
213 return o;
216 /* Handle variable-expansion-time functions such as $(dir foo/bar) ==> foo/ */
218 /* These enumeration constants distinguish the
219 various expansion-time built-in functions. */
221 enum function
223 function_subst,
224 function_addsuffix,
225 function_addprefix,
226 function_dir,
227 function_notdir,
228 function_suffix,
229 function_basename,
230 function_wildcard,
231 function_firstword,
232 function_word,
233 function_words,
234 function_wordlist,
235 function_findstring,
236 function_strip,
237 function_join,
238 function_patsubst,
239 function_filter,
240 function_filter_out,
241 function_foreach,
242 function_sort,
243 function_origin,
244 function_shell,
245 function_invalid
248 /* Greater than the length of any function name. */
249 #define MAXFUNCTIONLEN 11
251 /* The function names and lengths of names, for looking them up. */
253 static struct
255 char *name;
256 unsigned int len;
257 enum function function;
258 } function_table[] =
260 { "subst", 5, function_subst },
261 { "addsuffix", 9, function_addsuffix },
262 { "addprefix", 9, function_addprefix },
263 { "dir", 3, function_dir },
264 { "notdir", 6, function_notdir },
265 { "suffix", 6, function_suffix },
266 { "basename", 8, function_basename },
267 { "wildcard", 8, function_wildcard },
268 { "firstword", 9, function_firstword },
269 { "word", 4, function_word },
270 { "words", 5, function_words },
271 { "wordlist", 8, function_wordlist },
272 { "findstring", 10, function_findstring },
273 { "strip", 5, function_strip },
274 { "join", 4, function_join },
275 { "patsubst", 8, function_patsubst },
276 { "filter", 6, function_filter },
277 { "filter-out", 10, function_filter_out },
278 { "foreach", 7, function_foreach },
279 { "sort", 4, function_sort },
280 { "origin", 6, function_origin },
281 { "shell", 5, function_shell },
282 { 0, 0, function_invalid }
285 /* Return 1 if PATTERN matches WORD, 0 if not. */
288 pattern_matches (pattern, percent, word)
289 register char *pattern, *percent, *word;
291 unsigned int sfxlen, wordlen;
293 if (percent == 0)
295 unsigned int len = strlen (pattern) + 1;
296 char *new = (char *) alloca (len);
297 bcopy (pattern, new, len);
298 pattern = new;
299 percent = find_percent (pattern);
300 if (percent == 0)
301 return streq (pattern, word);
304 sfxlen = strlen (percent + 1);
305 wordlen = strlen (word);
307 if (wordlen < (percent - pattern) + sfxlen
308 || strncmp (pattern, word, percent - pattern))
309 return 0;
311 return !strcmp (percent + 1, word + (wordlen - sfxlen));
314 int shell_function_pid = 0, shell_function_completed;
316 /* Perform the function specified by FUNCTION on the text at TEXT.
317 END is points to the end of the argument text (exclusive).
318 The output is written into VARIABLE_BUFFER starting at O. */
320 /* Note this absorbs a semicolon and is safe to use in conditionals. */
321 #define BADARGS(func) \
322 if (reading_filename != 0) \
323 makefile_fatal (reading_filename, *reading_lineno_ptr, \
324 "insufficient arguments to function `%s'", \
325 func); \
326 else \
327 fatal ("insufficient arguments to function `%s'", func)
329 static char *
330 expand_function (o, function, text, end)
331 char *o;
332 enum function function;
333 char *text;
334 char *end;
336 char *p, *p2, *p3;
337 unsigned int i, j, len;
338 int doneany = 0;
339 int count;
340 char endparen = *end, startparen = *end == ')' ? '(' : '{';
342 switch (function)
344 default:
345 abort ();
346 break;
348 #ifndef VMS /* not supported for vms yet */
349 case function_shell:
351 #ifdef WINDOWS32
352 SECURITY_ATTRIBUTES saAttr;
353 HANDLE hIn;
354 HANDLE hErr;
355 HANDLE hChildOutRd;
356 HANDLE hChildOutWr;
357 HANDLE hProcess;
358 #endif
359 #ifdef __MSDOS__
360 FILE *fpipe;
361 #endif
362 char **argv;
363 char *error_prefix;
364 #ifndef _AMIGA
365 char **envp;
366 int pipedes[2];
367 int pid;
368 #endif
370 /* Expand the command line. */
371 text = expand_argument (text, end);
373 #ifndef __MSDOS__
374 /* Construct the argument list. */
375 argv = construct_command_argv (text,
376 (char **) NULL, (struct file *) 0);
377 if (argv == 0)
378 break;
379 #endif
381 #ifndef _AMIGA
382 /* Using a target environment for `shell' loses in cases like:
383 export var = $(shell echo foobie)
384 because target_environment hits a loop trying to expand $(var)
385 to put it in the environment. This is even more confusing when
386 var was not explicitly exported, but just appeared in the
387 calling environment. */
388 #if 1
389 envp = environ;
390 #else
391 /* Construct the environment. */
392 envp = target_environment ((struct file *) 0);
393 #endif
394 #endif /* Not Amiga. */
396 /* For error messages. */
397 if (reading_filename != 0)
399 error_prefix = (char *) alloca (strlen (reading_filename) + 100);
400 sprintf (error_prefix,
401 "%s:%u: ", reading_filename, *reading_lineno_ptr);
403 else
404 error_prefix = "";
406 #ifndef _AMIGA
407 # ifdef WINDOWS32
408 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
409 saAttr.bInheritHandle = TRUE;
410 saAttr.lpSecurityDescriptor = NULL;
412 if (DuplicateHandle(GetCurrentProcess(),
413 GetStdHandle(STD_INPUT_HANDLE),
414 GetCurrentProcess(),
415 &hIn,
417 TRUE,
418 DUPLICATE_SAME_ACCESS) == FALSE) {
419 fatal("create_child_process: DuplicateHandle(In) failed (e=%d)\n",
420 GetLastError());
422 if (DuplicateHandle(GetCurrentProcess(),
423 GetStdHandle(STD_ERROR_HANDLE),
424 GetCurrentProcess(),
425 &hErr,
427 TRUE,
428 DUPLICATE_SAME_ACCESS) == FALSE) {
429 fatal("create_child_process: DuplicateHandle(Err) failed (e=%d)\n",
430 GetLastError());
433 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
434 fatal("CreatePipe() failed (e=%d)\n", GetLastError());
436 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
438 if (!hProcess)
439 fatal("expand_function: process_init_fd() failed\n");
440 else
441 process_register(hProcess);
443 /* make sure that CreateProcess() has Path it needs */
444 sync_Path_environment();
446 if (!process_begin(hProcess, argv, envp, argv[0], NULL))
447 pid = (int) hProcess;
448 else
449 fatal("expand_function: unable to launch process (e=%d)\n",
450 process_last_err(hProcess));
452 /* set up to read data from child */
453 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
455 /* this will be closed almost right away */
456 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
457 # else /* WINDOWS32 */
458 # ifdef __MSDOS__
460 /* MSDOS can't fork, but it has `popen'.
461 (Bwt, why isn't `popen' used in all the versions?) */
462 struct variable *sh = lookup_variable ("SHELL", 5);
463 int e;
464 extern int dos_command_running, dos_status;
466 /* Make sure not to bother processing an empty line. */
467 while (isblank (*text))
468 ++text;
469 if (*text == '\0')
470 break;
472 if (sh)
474 char buf[PATH_MAX + 7];
475 /* This makes sure $SHELL value is used by $(shell), even
476 though the target environment is not passed to it. */
477 sprintf (buf, "SHELL=%s", sh->value);
478 putenv (buf);
481 e = errno;
482 errno = 0;
483 dos_command_running = 1;
484 dos_status = 0;
485 fpipe = popen (text, "rt");
486 dos_command_running = 0;
487 if (!fpipe || dos_status)
489 pipedes[0] = -1;
490 pid = -1;
491 if (dos_status)
492 errno = EINTR;
493 else if (errno == 0)
494 errno = ENOMEM;
495 shell_function_completed = -1;
497 else
499 pipedes[0] = fileno (fpipe);
500 pid = 42;
501 errno = e;
502 shell_function_completed = 1;
505 if (pipedes[0] < 0)
506 # else /* ! __MSDOS__ */
507 if (pipe (pipedes) < 0)
508 # endif /* __MSDOS__ */
510 perror_with_name (error_prefix, "pipe");
511 break;
514 # ifndef __MSDOS__
515 pid = vfork ();
516 if (pid < 0)
517 perror_with_name (error_prefix, "fork");
518 else if (pid == 0)
519 child_execute_job (0, pipedes[1], argv, envp);
520 else
521 # endif /* ! __MSDOS__ */
522 # endif /* WINDOWS32 */
524 /* We are the parent. */
526 char *buffer;
527 unsigned int maxlen;
528 int cc;
529 #if 0
530 for (i = 0; envp[i] != 0; ++i)
531 free (envp[i]);
532 free ((char *) envp);
533 #endif
535 /* Record the PID for reap_children. */
536 shell_function_pid = pid;
537 #ifndef __MSDOS__
538 shell_function_completed = 0;
540 /* Free the storage only the child needed. */
541 free (argv[0]);
542 free ((char *) argv);
544 /* Close the write side of the pipe. */
545 (void) close (pipedes[1]);
546 #endif
548 /* Set up and read from the pipe. */
550 maxlen = 200;
551 buffer = (char *) xmalloc (maxlen + 1);
553 /* Read from the pipe until it gets EOF. */
554 i = 0;
557 if (i == maxlen)
559 maxlen += 512;
560 buffer = (char *) xrealloc (buffer, maxlen + 1);
563 errno = 0;
564 cc = read (pipedes[0], &buffer[i], maxlen - i);
565 if (cc > 0)
566 i += cc;
568 #ifdef EINTR
569 while (cc > 0 || errno == EINTR);
570 #else
571 while (cc > 0);
572 #endif
574 /* Close the read side of the pipe. */
575 #ifdef __MSDOS__
576 if (fpipe)
577 (void) pclose (fpipe);
578 #else
579 (void) close (pipedes[0]);
580 #endif
582 /* Loop until child_handler sets shell_function_completed
583 to the status of our child shell. */
584 while (shell_function_completed == 0)
585 reap_children (1, 0);
587 shell_function_pid = 0;
589 /* The child_handler function will set shell_function_completed
590 to 1 when the child dies normally, or to -1 if it
591 dies with status 127, which is most likely an exec fail. */
593 if (shell_function_completed == -1)
595 /* This most likely means that the execvp failed,
596 so we should just write out the error message
597 that came in over the pipe from the child. */
598 fputs (buffer, stderr);
599 fflush (stderr);
601 else
603 /* The child finished normally. Replace all
604 newlines in its output with spaces, and put
605 that in the variable output buffer. */
606 if (i > 0)
608 if (buffer[i - 1] == '\n')
609 buffer[--i] = '\0';
610 else
611 buffer[i] = '\0';
612 p = buffer;
613 while ((p = index (p, '\n')) != 0)
614 *p++ = ' ';
615 o = variable_buffer_output (o, buffer, i);
619 free (buffer);
621 #else /* Amiga */
623 /* Amiga can't fork nor spawn, but I can start a program with
624 redirection of my choice. However, this means that we
625 don't have an opportunity to reopen stdout to trap it. Thus,
626 we save our own stdout onto a new descriptor and dup a temp
627 file's descriptor onto our stdout temporarily. After we
628 spawn the shell program, we dup our own stdout back to the
629 stdout descriptor. The buffer reading is the same as above,
630 except that we're now reading from a file. */
631 #include <dos/dos.h>
632 #include <proto/dos.h>
634 BPTR child_stdout;
635 char tmp_output[FILENAME_MAX];
636 unsigned int maxlen = 200;
637 int cc;
638 char * buffer, * ptr;
639 char ** aptr;
640 int len = 0;
642 strcpy (tmp_output, "t:MakeshXXXXXXXX");
643 mktemp (tmp_output);
644 child_stdout = Open (tmp_output, MODE_NEWFILE);
646 for (aptr=argv; *aptr; aptr++)
648 len += strlen (*aptr) + 1;
651 buffer = xmalloc (len + 1);
652 ptr = buffer;
654 for (aptr=argv; *aptr; aptr++)
656 strcpy (ptr, *aptr);
657 ptr += strlen (ptr) + 1;
658 *ptr ++ = ' ';
659 *ptr = 0;
662 ptr[-1] = '\n';
664 Execute (buffer, NULL, child_stdout);
665 free (buffer);
667 Close (child_stdout);
669 child_stdout = Open (tmp_output, MODE_OLDFILE);
671 buffer = xmalloc (maxlen);
672 i = 0;
675 if (i == maxlen)
677 maxlen += 512;
678 buffer = (char *) xrealloc (buffer, maxlen + 1);
681 cc = Read (child_stdout, &buffer[i], maxlen - i);
682 if (cc > 0)
683 i += cc;
684 } while (cc > 0);
686 Close (child_stdout);
687 DeleteFile (tmp_output);
689 if (i > 0)
691 if (buffer[i - 1] == '\n')
692 buffer[--i] = '\0';
693 else
694 buffer[i] = '\0';
695 p = buffer;
696 while ((p = index (p, '\n')) != 0)
697 *p++ = ' ';
698 o = variable_buffer_output (o, buffer, i);
700 free (buffer);
702 #endif /* Not Amiga. */
704 free (text);
705 break;
707 #endif /* !VMS */
709 case function_origin:
710 /* Expand the argument. */
711 text = expand_argument (text, end);
714 register struct variable *v = lookup_variable (text, strlen (text));
715 if (v == 0)
716 o = variable_buffer_output (o, "undefined", 9);
717 else
718 switch (v->origin)
720 default:
721 case o_invalid:
722 abort ();
723 break;
724 case o_default:
725 o = variable_buffer_output (o, "default", 7);
726 break;
727 case o_env:
728 o = variable_buffer_output (o, "environment", 11);
729 break;
730 case o_file:
731 o = variable_buffer_output (o, "file", 4);
732 break;
733 case o_env_override:
734 o = variable_buffer_output (o, "environment override", 20);
735 break;
736 case o_command:
737 o = variable_buffer_output (o, "command line", 12);
738 break;
739 case o_override:
740 o = variable_buffer_output (o, "override", 8);
741 break;
742 case o_automatic:
743 o = variable_buffer_output (o, "automatic", 9);
744 break;
748 free (text);
749 break;
751 case function_sort:
752 /* Expand the argument. */
753 text = expand_argument (text, end);
756 char **words = (char **) xmalloc (10 * sizeof (char *));
757 unsigned int nwords = 10;
758 register unsigned int wordi = 0;
759 char *t;
761 /* Chop TEXT into words and put them in WORDS. */
762 t = text;
763 while ((p = find_next_token (&t, &len)) != 0)
765 if (wordi >= nwords - 1)
767 nwords *= 2;
768 words = (char **) xrealloc ((char *) words,
769 nwords * sizeof (char *));
771 words[wordi++] = savestring (p, len);
774 if (wordi > 0)
776 /* Now sort the list of words. */
777 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
779 /* Now write the sorted list. */
780 for (i = 0; i < wordi; ++i)
782 len = strlen (words[i]);
783 if (i == wordi - 1 || strlen (words[i + 1]) != len
784 || strcmp (words[i], words[i + 1]))
786 o = variable_buffer_output (o, words[i], len);
787 o = variable_buffer_output (o, " ", 1);
789 free (words[i]);
791 /* Kill the last space. */
792 --o;
795 free ((char *) words);
798 free (text);
799 break;
801 case function_foreach:
803 /* Get three comma-separated arguments but
804 expand only the first two. */
805 char *var, *list;
806 register struct variable *v;
808 count = 0;
809 for (p = text; p < end; ++p)
811 if (*p == startparen)
812 ++count;
813 else if (*p == endparen)
814 --count;
815 else if (*p == ',' && count <= 0)
816 break;
818 if (p == end)
819 BADARGS ("foreach");
820 var = expand_argument (text, p);
822 p2 = p + 1;
823 count = 0;
824 for (p = p2; p < end; ++p)
826 if (*p == startparen)
827 ++count;
828 else if (*p == endparen)
829 --count;
830 else if (*p == ',' && count <= 0)
831 break;
833 if (p == end)
834 BADARGS ("foreach");
835 list = expand_argument (p2, p);
837 ++p;
838 text = savestring (p, end - p);
840 push_new_variable_scope ();
841 v = define_variable (var, strlen (var), "", o_automatic, 0);
842 p3 = list;
843 while ((p = find_next_token (&p3, &len)) != 0)
845 char *result;
846 char save = p[len];
847 p[len] = '\0';
848 v->value = p;
849 result = allocated_variable_expand (text);
850 p[len] = save;
852 o = variable_buffer_output (o, result, strlen (result));
853 o = variable_buffer_output (o, " ", 1);
854 doneany = 1;
855 free (result);
857 if (doneany)
858 /* Kill the last space. */
859 --o;
861 pop_variable_scope ();
863 free (var);
864 free (list);
865 free (text);
867 break;
869 case function_filter:
870 case function_filter_out:
872 struct word
874 struct word *next;
875 char *word;
876 int matched;
877 } *words, *wordtail, *wp;
879 /* Get two comma-separated arguments and expand each one. */
880 count = 0;
881 for (p = text; p < end; ++p)
883 if (*p == startparen)
884 ++count;
885 else if (*p == endparen)
886 --count;
887 else if (*p == ',' && count <= 0)
888 break;
890 if (p == end)
891 BADARGS (function == function_filter ? "filter" : "filter-out");
892 p2 = expand_argument (text, p);
894 text = expand_argument (p + 1, end);
896 /* Chop TEXT up into words and then run each pattern through. */
897 words = wordtail = 0;
898 p3 = text;
899 while ((p = find_next_token (&p3, &len)) != 0)
901 struct word *w = (struct word *) alloca (sizeof (struct word));
902 if (words == 0)
903 words = w;
904 else
905 wordtail->next = w;
906 wordtail = w;
908 if (*p3 != '\0')
909 ++p3;
910 p[len] = '\0';
911 w->word = p;
912 w->matched = 0;
915 if (words != 0)
917 wordtail->next = 0;
919 /* Run each pattern through the words, killing words. */
920 p3 = p2;
921 while ((p = find_next_token (&p3, &len)) != 0)
923 char *percent;
924 char save = p[len];
925 p[len] = '\0';
927 percent = find_percent (p);
928 for (wp = words; wp != 0; wp = wp->next)
929 wp->matched |= (percent == 0 ? streq (p, wp->word)
930 : pattern_matches (p, percent, wp->word));
932 p[len] = save;
935 /* Output the words that matched (or didn't, for filter-out). */
936 for (wp = words; wp != 0; wp = wp->next)
937 if (function == function_filter ? wp->matched : !wp->matched)
939 o = variable_buffer_output (o, wp->word, strlen (wp->word));
940 o = variable_buffer_output (o, " ", 1);
941 doneany = 1;
943 if (doneany)
944 /* Kill the last space. */
945 --o;
948 free (p2);
949 free (text);
951 break;
953 case function_patsubst:
954 /* Get three comma-separated arguments and expand each one. */
955 count = 0;
956 for (p = text; p < end; ++p)
958 if (*p == startparen)
959 ++count;
960 else if (*p == endparen)
961 --count;
962 else if (*p == ',' && count <= 0)
963 break;
965 if (p == end)
966 BADARGS ("patsubst");
968 p2 = p;
969 count = 0;
970 for (++p; p < end; ++p)
972 if (*p == startparen)
973 ++count;
974 else if (*p == endparen)
975 --count;
976 else if (*p == ',' && count <= 0)
977 break;
979 if (p == end)
980 BADARGS ("patsubst");
982 text = expand_argument (text, p2);
983 p3 = expand_argument (p2 + 1, p);
984 p2 = expand_argument (p + 1, end);
986 o = patsubst_expand (o, p2, text, p3, (char *) 0, (char *) 0);
988 free (text);
989 free (p3);
990 free (p2);
991 break;
993 case function_join:
994 /* Get two comma-separated arguments and expand each one. */
995 count = 0;
996 for (p = text; p < end; ++p)
998 if (*p == startparen)
999 ++count;
1000 else if (*p == endparen)
1001 --count;
1002 else if (*p == ',' && count <= 0)
1003 break;
1005 if (p == end)
1006 BADARGS ("join");
1007 text = expand_argument (text, p);
1009 p = expand_argument (p + 1, end);
1012 /* Write each word of the first argument directly followed
1013 by the corresponding word of the second argument.
1014 If the two arguments have a different number of words,
1015 the excess words are just output separated by blanks. */
1016 register char *tp, *pp;
1017 p2 = text;
1018 p3 = p;
1021 unsigned int tlen, plen;
1023 tp = find_next_token (&p2, &tlen);
1024 if (tp != 0)
1025 o = variable_buffer_output (o, tp, tlen);
1027 pp = find_next_token (&p3, &plen);
1028 if (pp != 0)
1029 o = variable_buffer_output (o, pp, plen);
1031 if (tp != 0 || pp != 0)
1033 o = variable_buffer_output (o, " ", 1);
1034 doneany = 1;
1037 while (tp != 0 || pp != 0);
1038 if (doneany)
1039 /* Kill the last blank. */
1040 --o;
1043 free (text);
1044 free (p);
1045 break;
1047 case function_strip:
1048 /* Expand the argument. */
1049 text = expand_argument (text, end);
1051 p2 = text;
1052 while ((p = find_next_token (&p2, &i)) != 0)
1054 o = variable_buffer_output (o, p, i);
1055 o = variable_buffer_output (o, " ", 1);
1056 doneany = 1;
1058 if (doneany)
1059 /* Kill the last space. */
1060 --o;
1062 free (text);
1063 break;
1065 case function_wildcard:
1066 text = expand_argument (text, end);
1068 #ifdef _AMIGA
1069 o = wildcard_expansion (text, o);
1070 #else
1071 p = string_glob (text);
1072 o = variable_buffer_output (o, p, strlen (p));
1073 #endif
1075 free (text);
1076 break;
1078 case function_subst:
1079 /* Get three comma-separated arguments and expand each one. */
1080 count = 0;
1081 for (p = text; p < end; ++p)
1083 if (*p == startparen)
1084 ++count;
1085 else if (*p == endparen)
1086 --count;
1087 else if (*p == ',' && count <= 0)
1088 break;
1090 if (p == end)
1091 BADARGS ("subst");
1093 p2 = p;
1094 count = 0;
1095 for (++p; p < end; ++p)
1097 if (*p == startparen)
1098 ++count;
1099 else if (*p == endparen)
1100 --count;
1101 else if (*p == ',' && count <= 0)
1102 break;
1104 if (p == end)
1105 BADARGS ("subst");
1107 text = expand_argument (text, p2);
1108 p3 = expand_argument (p2 + 1, p);
1109 p2 = expand_argument (p + 1, end);
1111 o = subst_expand (o, p2, text, p3, strlen (text), strlen (p3), 0, 0);
1113 free (text);
1114 free (p3);
1115 free (p2);
1116 break;
1118 case function_firstword:
1119 /* Expand the argument. */
1120 text = expand_argument (text, end);
1122 /* Find the first word in TEXT. */
1123 p2 = text;
1124 p = find_next_token (&p2, &i);
1125 if (p != 0)
1126 o = variable_buffer_output (o, p, i);
1128 free (text);
1129 break;
1131 case function_word:
1132 /* Get two comma-separated arguments and expand each one. */
1133 count = 0;
1134 for (p = text; p < end; ++p)
1136 if (*p == startparen)
1137 ++count;
1138 else if (*p == endparen)
1139 --count;
1140 else if (*p == ',' && count <= 0)
1141 break;
1143 if (p == end)
1144 BADARGS ("word");
1145 text = expand_argument (text, p);
1147 p3 = expand_argument (p + 1, end);
1149 /* Check the first argument. */
1150 for (p2 = text; *p2 != '\0'; ++p2)
1151 if (*p2 < '0' || *p2 > '9')
1153 if (reading_filename != 0)
1154 makefile_fatal (reading_filename, *reading_lineno_ptr,
1155 "non-numeric first argument to `word' function");
1156 else
1157 fatal ("non-numeric first argument to `word' function");
1160 i = (unsigned int) atoi (text);
1161 if (i == 0)
1163 if (reading_filename != 0)
1164 makefile_fatal (reading_filename, *reading_lineno_ptr,
1165 "the `word' function takes a one-origin \
1166 index argument");
1167 else
1168 fatal ("the `word' function takes a one-origin index argument");
1171 p2 = p3;
1172 while ((p = find_next_token (&p2, &len)) != 0)
1173 if (--i == 0)
1174 break;
1175 if (i == 0)
1176 o = variable_buffer_output (o, p, len);
1178 free (text);
1179 free (p3);
1180 break;
1182 case function_words:
1183 /* Expand the argument. */
1184 text = expand_argument (text, end);
1186 i = 0;
1187 p2 = text;
1188 while (find_next_token (&p2, (unsigned int *) 0) != 0)
1189 ++i;
1192 char buf[20];
1193 sprintf (buf, "%d", i);
1194 o = variable_buffer_output (o, buf, strlen (buf));
1197 free (text);
1198 break;
1200 case function_wordlist:
1201 /* Get two comma-separated arguments and expand each one. */
1202 count = 0;
1203 for (p = text; p < end; ++p)
1205 if (*p == startparen)
1206 ++count;
1207 else if (*p == endparen)
1208 --count;
1209 else if (*p == ',' && count <= 0)
1210 break;
1212 if (p == end)
1213 BADARGS ("wordlist");
1214 text = expand_argument (text, p);
1216 /* Check the first argument. */
1217 for (p2 = text; *p2 != '\0'; ++p2)
1218 if (*p2 < '0' || *p2 > '9')
1220 if (reading_filename != 0)
1221 makefile_fatal (reading_filename, *reading_lineno_ptr,
1222 "non-numeric first argument to `wordlist' function");
1223 else
1224 fatal ("non-numeric first argument to `wordlist' function");
1226 i = (unsigned int)atoi(text);
1227 free (text);
1229 /* Check the next argument */
1230 for (p2 = p + 1; isblank(*p2); ++p2)
1232 count = 0;
1233 for (p = p2; p < end; ++p)
1235 if (*p == startparen)
1236 ++count;
1237 else if (*p == endparen)
1238 --count;
1239 else if (*p == ',' && count <= 0)
1240 break;
1242 if (p == end)
1243 BADARGS ("wordlist");
1244 text = expand_argument (p2, p);
1246 for (p2 = text; *p2 != '\0'; ++p2)
1247 if (*p2 < '0' || *p2 > '9')
1249 if (reading_filename != 0)
1250 makefile_fatal (reading_filename, *reading_lineno_ptr,
1251 "non-numeric second argument to `wordlist' function");
1252 else
1253 fatal ("non-numeric second argument to `wordlist' function");
1255 j = (unsigned int)atoi(text);
1256 free (text);
1258 if (j > i)
1259 j -= i;
1260 else
1262 unsigned int k;
1263 k = j;
1264 j = i - j;
1265 i = k;
1267 ++j;
1269 /* Extract the requested words */
1270 text = expand_argument (p + 1, end);
1271 p2 = text;
1273 while (((p = find_next_token (&p2, &len)) != 0) && --i)
1275 if (p)
1277 while (--j && (find_next_token (&p2, &len) != 0))
1279 o = variable_buffer_output (o, p, p2 - p);
1282 free (text);
1283 break;
1285 case function_findstring:
1286 /* Get two comma-separated arguments and expand each one. */
1287 count = 0;
1288 for (p = text; p < end; ++p)
1290 if (*p == startparen)
1291 ++count;
1292 else if (*p == endparen)
1293 --count;
1294 else if (*p == ',' && count <= 0)
1295 break;
1297 if (p == end)
1298 BADARGS ("findstring");
1299 text = expand_argument (text, p);
1301 p = expand_argument (p + 1, end);
1303 /* Find the first occurrence of the first string in the second. */
1304 i = strlen (text);
1305 if (sindex (p, 0, text, i) != 0)
1306 o = variable_buffer_output (o, text, i);
1308 free (p);
1309 free (text);
1310 break;
1312 case function_addsuffix:
1313 case function_addprefix:
1314 /* Get two comma-separated arguments and expand each one. */
1315 count = 0;
1316 for (p = text; p < end; ++p)
1318 if (*p == startparen)
1319 ++count;
1320 else if (*p == endparen)
1321 --count;
1322 else if (*p == ',' && count <= 0)
1323 break;
1325 if (p == end)
1326 BADARGS (function == function_addsuffix ? "addsuffix" : "addprefix");
1327 text = expand_argument (text, p);
1328 i = strlen (text);
1330 p2 = expand_argument (p + 1, end);
1332 p3 = p2;
1333 while ((p = find_next_token (&p3, &len)) != 0)
1335 if (function == function_addprefix)
1336 o = variable_buffer_output (o, text, i);
1337 o = variable_buffer_output (o, p, len);
1338 if (function == function_addsuffix)
1339 o = variable_buffer_output (o, text, i);
1340 o = variable_buffer_output (o, " ", 1);
1341 doneany = 1;
1343 if (doneany)
1344 /* Kill last space. */
1345 --o;
1347 free (p2);
1348 free (text);
1349 break;
1351 case function_dir:
1352 case function_basename:
1353 /* Expand the argument. */
1354 text = expand_argument (text, end);
1356 p3 = text;
1357 while ((p2 = find_next_token (&p3, &len)) != 0)
1359 p = p2 + len;
1360 #ifdef VMS
1361 while (p >= p2 && *p != ']'
1362 && (function != function_basename || *p != '.'))
1363 #else
1364 # ifdef __MSDOS__
1365 while (p >= p2 && *p != '/' && *p != '\\'
1366 && (function != function_basename || *p != '.'))
1367 # else
1368 while (p >= p2 && *p != '/'
1369 && (function != function_basename || *p != '.'))
1370 # endif
1371 #endif
1372 --p;
1373 if (p >= p2 && (function == function_dir))
1374 o = variable_buffer_output (o, p2, ++p - p2);
1375 else if (p >= p2 && (*p == '.'))
1376 o = variable_buffer_output (o, p2, p - p2);
1377 #if defined(WINDOWS32) || defined(__MSDOS__)
1378 /* Handle the "d:foobar" case */
1379 else if (p2[0] && p2[1] == ':' && function == function_dir)
1380 o = variable_buffer_output (o, p2, 2);
1381 #endif
1382 else if (function == function_dir)
1383 #ifdef VMS
1384 o = variable_buffer_output (o, "[]", 2);
1385 #else
1386 #ifndef _AMIGA
1387 o = variable_buffer_output (o, "./", 2);
1388 #else
1389 /* o = o */; /* Just a nop... */
1390 #endif /* AMIGA */
1391 #endif /* !VMS */
1392 else
1393 /* The entire name is the basename. */
1394 o = variable_buffer_output (o, p2, len);
1396 o = variable_buffer_output (o, " ", 1);
1397 doneany = 1;
1399 if (doneany)
1400 /* Kill last space. */
1401 --o;
1403 free (text);
1404 break;
1406 case function_notdir:
1407 case function_suffix:
1408 /* Expand the argument. */
1409 text = expand_argument (text, end);
1411 p3 = text;
1412 while ((p2 = find_next_token (&p3, &len)) != 0)
1414 p = p2 + len;
1415 #ifdef VMS
1416 while (p >= p2 && *p != ']'
1417 && (function != function_suffix || *p != '.'))
1418 #else
1419 # ifdef __MSDOS__
1420 while (p >= p2 && *p != '/' && *p != '\\'
1421 && (function != function_suffix || *p != '.'))
1422 # else
1423 while (p >= p2 && *p != '/'
1424 && (function != function_suffix || *p != '.'))
1425 # endif
1426 #endif
1427 --p;
1428 if (p >= p2)
1430 if (function == function_notdir)
1431 ++p;
1432 else if (*p != '.')
1433 continue;
1434 o = variable_buffer_output (o, p, len - (p - p2));
1436 #if defined(WINDOWS32) || defined(__MSDOS__)
1437 /* Handle the case of "d:foo/bar". */
1438 else if (function == function_notdir && p2[0] && p2[1] == ':')
1440 p = p2 + 2;
1441 o = variable_buffer_output (o, p, len - (p - p2));
1443 #endif
1444 else if (function == function_notdir)
1445 o = variable_buffer_output (o, p2, len);
1447 if (function == function_notdir || p >= p2)
1449 o = variable_buffer_output (o, " ", 1);
1450 doneany = 1;
1453 if (doneany)
1454 /* Kill last space. */
1455 --o;
1457 free (text);
1458 break;
1461 return o;
1464 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1465 opening ( or { and is not null-terminated. If a function invocation
1466 is found, expand it into the buffer at *OP, updating *OP, incrementing
1467 *STRINGP past the reference and returning nonzero. If not, return zero. */
1470 handle_function (op, stringp)
1471 char **op;
1472 char **stringp;
1475 register unsigned int code;
1476 unsigned int maxlen;
1477 char *beg = *stringp + 1;
1478 char *endref;
1480 endref = lindex (beg, beg + MAXFUNCTIONLEN, '\0');
1481 maxlen = endref != 0 ? endref - beg : MAXFUNCTIONLEN;
1483 for (code = 0; function_table[code].name != 0; ++code)
1485 if (maxlen < function_table[code].len)
1486 continue;
1487 endref = beg + function_table[code].len;
1488 if (isblank (*endref)
1489 && !strncmp (function_table[code].name, beg,
1490 function_table[code].len))
1491 break;
1493 if (function_table[code].name != 0)
1495 /* We have found a call to an expansion-time function.
1496 Find the end of the arguments, and do the function. */
1498 char openparen = beg[-1], closeparen = openparen == '(' ? ')' : '}';
1499 int count = 0;
1500 char *argbeg;
1501 register char *p;
1503 /* Space after function name isn't part of the args. */
1504 p = next_token (endref);
1505 argbeg = p;
1507 /* Count nested use of whichever kind of parens we use,
1508 so that nested calls and variable refs work. */
1510 for (; *p != '\0'; ++p)
1512 if (*p == openparen)
1513 ++count;
1514 else if (*p == closeparen && --count < 0)
1515 break;
1518 if (count >= 0)
1520 static const char errmsg[]
1521 = "unterminated call to function `%s': missing `%c'";
1522 if (reading_filename == 0)
1523 fatal (errmsg, function_table[code].name, closeparen);
1524 else
1525 makefile_fatal (reading_filename, *reading_lineno_ptr, errmsg,
1526 function_table[code].name, closeparen);
1529 /* We found the end; expand the function call. */
1531 *op = expand_function (*op, function_table[code].function, argbeg, p);
1532 *stringp = p;
1533 return 1;
1536 return 0;
1539 /* Glob-expand LINE. The returned pointer is
1540 only good until the next call to string_glob. */
1542 static char *
1543 string_glob (line)
1544 char *line;
1546 static char *result = 0;
1547 static unsigned int length;
1548 register struct nameseq *chain;
1549 register unsigned int idx;
1551 chain = multi_glob (parse_file_seq
1552 (&line, '\0', sizeof (struct nameseq),
1553 /* We do not want parse_file_seq to strip `./'s.
1554 That would break examples like:
1555 $(patsubst ./%.c,obj/%.o,$(wildcard ./*.c)). */
1557 sizeof (struct nameseq));
1559 if (result == 0)
1561 length = 100;
1562 result = (char *) xmalloc (100);
1565 idx = 0;
1566 while (chain != 0)
1568 register char *name = chain->name;
1569 unsigned int len = strlen (name);
1571 struct nameseq *next = chain->next;
1572 free ((char *) chain);
1573 chain = next;
1575 /* multi_glob will pass names without globbing metacharacters
1576 through as is, but we want only files that actually exist. */
1577 if (file_exists_p (name))
1579 if (idx + len + 1 > length)
1581 length += (len + 1) * 2;
1582 result = (char *) xrealloc (result, length);
1584 bcopy (name, &result[idx], len);
1585 idx += len;
1586 result[idx++] = ' ';
1589 free (name);
1592 /* Kill the last space and terminate the string. */
1593 if (idx == 0)
1594 result[0] = '\0';
1595 else
1596 result[idx - 1] = '\0';
1598 return result;