a6fadf07a27f974d8caf473544335c8335e38b03
[dragonfly.git] / usr.bin / make / str.c
1 /*-
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1989 by Berkeley Softworks
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * @(#)str.c    5.8 (Berkeley) 6/1/90
39  * $FreeBSD: src/usr.bin/make/str.c,v 1.12.2.2 2004/02/23 12:10:57 ru Exp $
40  * $DragonFly: src/usr.bin/make/str.c,v 1.11 2004/12/16 00:17:05 okumoto Exp $
41  */
42
43 #include "make.h"
44
45 static char **argv, *buffer;
46 static int argmax, curlen;
47
48 /*
49  * str_init --
50  *      Initialize the strings package
51  *
52  */
53 void
54 str_init(void)
55 {
56     char *p1;
57
58     argv = emalloc(((argmax = 50) + 1) * sizeof(char *));
59     argv[0] = Var_Value(".MAKE", VAR_GLOBAL, &p1);
60 }
61
62
63 /*
64  * str_end --
65  *      Cleanup the strings package
66  *
67  */
68 void
69 str_end(void)
70 {
71     if (argv) {
72         if (argv[0])
73             free(argv[0]);
74         free(argv);
75     }
76     if (buffer)
77         free(buffer);
78 }
79
80 /*-
81  * str_concat --
82  *      concatenate the two strings, inserting a space or slash between them,
83  *      freeing them if requested.
84  *
85  * returns --
86  *      the resulting string in allocated space.
87  */
88 char *
89 str_concat(const char *s1, const char *s2, int flags)
90 {
91         int len1, len2;
92         char *result;
93
94         /* get the length of both strings */
95         len1 = strlen(s1);
96         len2 = strlen(s2);
97
98         /* allocate length plus separator plus EOS */
99         result = emalloc(len1 + len2 + 2);
100
101         /* copy first string into place */
102         memcpy(result, s1, len1);
103
104         /* add separator character */
105         if (flags & STR_ADDSPACE) {
106                 result[len1] = ' ';
107                 ++len1;
108         } else if (flags & STR_ADDSLASH) {
109                 result[len1] = '/';
110                 ++len1;
111         }
112
113         /* copy second string plus EOS into place */
114         memcpy(result + len1, s2, len2 + 1);
115         return (result);
116 }
117
118 /*-
119  * brk_string --
120  *      Fracture a string into an array of words (as delineated by tabs or
121  *      spaces) taking quotation marks into account.  Leading tabs/spaces
122  *      are ignored.
123  *
124  * returns --
125  *      Pointer to the array of pointers to the words.  To make life easier,
126  *      the first word is always the value of the .MAKE variable.
127  */
128 char **
129 brk_string(char *str, int *store_argc, Boolean expand)
130 {
131         int argc, ch;
132         char inquote, *p, *start, *t;
133         int len;
134
135         /* skip leading space chars. */
136         for (; *str == ' ' || *str == '\t'; ++str)
137                 continue;
138
139         /* allocate room for a copy of the string */
140         if ((len = strlen(str) + 1) > curlen) {
141                 if (buffer)
142                     free(buffer);
143                 buffer = emalloc(curlen = len);
144         }
145
146         /*
147          * copy the string; at the same time, parse backslashes,
148          * quotes and build the argument list.
149          */
150         argc = 1;
151         inquote = '\0';
152         for (p = str, start = t = buffer;; ++p) {
153                 switch(ch = *p) {
154                 case '"':
155                 case '\'':
156                         if (inquote) {
157                                 if (ch != inquote)
158                                         break;
159                                 inquote = '\0';
160                                 /* Don't miss "" or '' */
161                                 if (!start)
162                                         start = t;
163                         } else
164                                 inquote = (char)ch;
165                         if (expand)
166                                 continue;
167                         break;
168                 case ' ':
169                 case '\t':
170                 case '\n':
171                         if (inquote)
172                                 break;
173                         if (!start)
174                                 continue;
175                         /* FALLTHROUGH */
176                 case '\0':
177                         /*
178                          * end of a token -- make sure there's enough argv
179                          * space and save off a pointer.
180                          */
181                         if (!start)
182                             goto done;
183
184                         *t++ = '\0';
185                         if (argc == argmax) {
186                                 argmax *= 2;            /* ramp up fast */
187                                 argv = erealloc(argv,
188                                     (argmax + 1) * sizeof(char *));
189                         }
190                         argv[argc++] = start;
191                         start = NULL;
192                         if (ch == '\n' || ch == '\0')
193                                 goto done;
194                         continue;
195                 case '\\':
196                         if (!expand) {
197                                 if (!start)
198                                         start = t;
199                                 *t++ = '\\';
200                                 ch = *++p;
201                                 break;
202                         }
203
204                         switch (ch = *++p) {
205                         case '\0':
206                         case '\n':
207                                 /* hmmm; fix it up as best we can */
208                                 ch = '\\';
209                                 --p;
210                                 break;
211                         case 'b':
212                                 ch = '\b';
213                                 break;
214                         case 'f':
215                                 ch = '\f';
216                                 break;
217                         case 'n':
218                                 ch = '\n';
219                                 break;
220                         case 'r':
221                                 ch = '\r';
222                                 break;
223                         case 't':
224                                 ch = '\t';
225                                 break;
226                         default:
227                                 break;
228                         }
229                         break;
230                 default:
231                         break;
232                 }
233                 if (!start)
234                         start = t;
235                 *t++ = (char)ch;
236         }
237 done:   argv[argc] = NULL;
238         *store_argc = argc;
239         return (argv);
240 }
241
242 /*
243  * Str_Match --
244  *
245  * See if a particular string matches a particular pattern.
246  *
247  * Results: Non-zero is returned if string matches pattern, 0 otherwise. The
248  * matching operation permits the following special characters in the
249  * pattern: *?\[] (see the man page for details on what these mean).
250  *
251  * Side effects: None.
252  */
253 int
254 Str_Match(const char *string, const char *pattern)
255 {
256         char c2;
257
258         for (;;) {
259                 /*
260                  * See if we're at the end of both the pattern and the
261                  * string. If, we succeeded.  If we're at the end of the
262                  * pattern but not at the end of the string, we failed.
263                  */
264                 if (*pattern == 0)
265                         return (!*string);
266                 if (*string == 0 && *pattern != '*')
267                         return (0);
268                 /*
269                  * Check for a "*" as the next pattern character.  It matches
270                  * any substring.  We handle this by calling ourselves
271                  * recursively for each postfix of string, until either we
272                  * match or we reach the end of the string.
273                  */
274                 if (*pattern == '*') {
275                         pattern += 1;
276                         if (*pattern == 0)
277                                 return (1);
278                         while (*string != 0) {
279                                 if (Str_Match(string, pattern))
280                                         return (1);
281                                 ++string;
282                         }
283                         return (0);
284                 }
285                 /*
286                  * Check for a "?" as the next pattern character.  It matches
287                  * any single character.
288                  */
289                 if (*pattern == '?')
290                         goto thisCharOK;
291                 /*
292                  * Check for a "[" as the next pattern character.  It is
293                  * followed by a list of characters that are acceptable, or
294                  * by a range (two characters separated by "-").
295                  */
296                 if (*pattern == '[') {
297                         ++pattern;
298                         for (;;) {
299                                 if ((*pattern == ']') || (*pattern == 0))
300                                         return (0);
301                                 if (*pattern == *string)
302                                         break;
303                                 if (pattern[1] == '-') {
304                                         c2 = pattern[2];
305                                         if (c2 == 0)
306                                                 return (0);
307                                         if ((*pattern <= *string) &&
308                                             (c2 >= *string))
309                                                 break;
310                                         if ((*pattern >= *string) &&
311                                             (c2 <= *string))
312                                                 break;
313                                         pattern += 2;
314                                 }
315                                 ++pattern;
316                         }
317                         while ((*pattern != ']') && (*pattern != 0))
318                                 ++pattern;
319                         goto thisCharOK;
320                 }
321                 /*
322                  * If the next pattern character is '/', just strip off the
323                  * '/' so we do exact matching on the character that follows.
324                  */
325                 if (*pattern == '\\') {
326                         ++pattern;
327                         if (*pattern == 0)
328                                 return (0);
329                 }
330                 /*
331                  * There's no special character.  Just make sure that the
332                  * next characters of each string match.
333                  */
334                 if (*pattern != *string)
335                         return (0);
336 thisCharOK:     ++pattern;
337                 ++string;
338         }
339 }
340
341
342 /*-
343  *-----------------------------------------------------------------------
344  * Str_SYSVMatch --
345  *      Check word against pattern for a match (% is wild),
346  *
347  * Results:
348  *      Returns the beginning position of a match or null. The number
349  *      of characters matched is returned in len.
350  *
351  * Side Effects:
352  *      None
353  *
354  *-----------------------------------------------------------------------
355  */
356 const char *
357 Str_SYSVMatch(const char *word, const char *pattern, int *len)
358 {
359     const char *p = pattern;
360     const char *w = word;
361     const char *m;
362
363     if (*w == '\0') {
364         /* Zero-length word cannot be matched against */
365         *len = 0;
366         return (NULL);
367     }
368
369     if (*p == '\0') {
370         /* Null pattern is the whole string */
371         *len = strlen(w);
372         return (w);
373     }
374
375     if ((m = strchr(p, '%')) != NULL) {
376         /* check that the prefix matches */
377         for (; p != m && *w && *w == *p; w++, p++)
378              continue;
379
380         if (p != m)
381             return (NULL);      /* No match */
382
383         if (*++p == '\0') {
384             /* No more pattern, return the rest of the string */
385             *len = strlen(w);
386             return (w);
387         }
388     }
389
390     m = w;
391
392     /* Find a matching tail */
393     do
394         if (strcmp(p, w) == 0) {
395             *len = w - m;
396             return (m);
397         }
398     while (*w++ != '\0');
399
400     return (NULL);
401 }
402
403
404 /*-
405  *-----------------------------------------------------------------------
406  * Str_SYSVSubst --
407  *      Substitute '%' on the pattern with len characters from src.
408  *      If the pattern does not contain a '%' prepend len characters
409  *      from src.
410  *
411  * Results:
412  *      None
413  *
414  * Side Effects:
415  *      Places result on buf
416  *
417  *-----------------------------------------------------------------------
418  */
419 void
420 Str_SYSVSubst(Buffer buf, const char *pat, const char *src, int len)
421 {
422     const char *m;
423
424     if ((m = strchr(pat, '%')) != NULL) {
425         /* Copy the prefix */
426         Buf_AddBytes(buf, m - pat, (Byte *)pat);
427         /* skip the % */
428         pat = m + 1;
429     }
430
431     /* Copy the pattern */
432     Buf_AddBytes(buf, len, (Byte *)src);
433
434     /* append the rest */
435     Buf_AddBytes(buf, strlen(pat), (Byte *)pat);
436 }