Remove spaces infront of tabs.
[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.40 2005/02/07 07:54:23 harti Exp $
40  * $DragonFly: src/usr.bin/make/str.c,v 1.35 2005/06/17 07:54:24 okumoto Exp $
41  */
42
43 #include <ctype.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include "buf.h"
48 #include "globals.h"
49 #include "str.h"
50 #include "util.h"
51
52 /**
53  * Initialize the argument array object.  The array is initially
54  * eight positions, and will be expaned as necessary.  The first
55  * position is set to NULL since everything ignores it.  We allocate
56  * (size + 1) since we need space for the terminating NULL.  The
57  * buffer is set to NULL, since no common buffer is allocated yet.
58  */
59 void
60 ArgArray_Init(ArgArray *aa)
61 {
62         aa->size = 8;
63         aa->argv = emalloc((aa->size + 1) * sizeof(char *));
64         aa->argc = 0;
65         aa->argv[aa->argc++] = NULL;
66         aa->len = 0;
67         aa->buffer = NULL;
68 }
69
70 /**
71  * Cleanup the memory allocated for in the argument array object.
72  */
73 void
74 ArgArray_Done(ArgArray *aa)
75 {
76         if (aa->buffer == NULL) {
77                 int     i;
78                 /* args are individually allocated */
79                 for (i = 0; i < aa->argc; ++i) {
80                         if (aa->argv[i]) {
81                                 free(aa->argv[i]);
82                                 aa->argv[i] = NULL;
83                         }
84                 }
85         } else {
86                 /* args are part of a single allocation */
87                 free(aa->buffer);
88                 aa->buffer = NULL;
89         }
90         free(aa->argv);
91         aa->argv = NULL;
92         aa->argc = 0;
93         aa->size = 0;
94 }
95
96 /**
97  * Concatenate the two strings, possibily inserting a character between them.
98  *
99  * @returns
100  *      the resulting string in allocated space.
101  */
102 char *
103 str_concat(const char s1[], char c, const char s2[])
104 {
105         int len1, len2;
106         char *result;
107
108         /* get the length of both strings */
109         len1 = strlen(s1);
110         len2 = strlen(s2);
111
112         /* allocate length plus separator plus EOS */
113         result = emalloc(len1 + len2 + 2);
114
115         /* copy first string into place */
116         memcpy(result, s1, len1);
117
118         /* add separator character */
119         if (c != '\0') {
120                 result[len1] = c;
121                 ++len1;
122         }
123
124         /* copy second string plus EOS into place */
125         memcpy(result + len1, s2, len2 + 1);
126
127         return (result);
128 }
129
130 /**
131  * Fracture a string into an array of words (as delineated by tabs or
132  * spaces) taking quotation marks into account.  Leading tabs/spaces
133  * are ignored.
134  */
135 void
136 brk_string(ArgArray *aa, const char str[], Boolean expand)
137 {
138         char    inquote;
139         char    *start;
140         char    *arg;
141
142         /* skip leading space chars. */
143         for (; *str == ' ' || *str == '\t'; ++str)
144                 continue;
145
146         ArgArray_Init(aa);
147
148         aa->buffer = estrdup(str);;
149
150         arg = aa->buffer;
151         start = arg;
152         inquote = '\0';
153
154         /*
155          * copy the string; at the same time, parse backslashes,
156          * quotes and build the argument list.
157          */
158         for (;;) {
159                 switch (str[0]) {
160                 case '"':
161                 case '\'':
162                         if (inquote == '\0') {
163                                 inquote = str[0];
164                                 if (expand)
165                                         break;
166                                 if (start == NULL)
167                                         start = arg;
168                         } else if (inquote == str[0]) {
169                                 inquote = '\0';
170                                 /* Don't miss "" or '' */
171                                 if (start == NULL)
172                                         start = arg;
173                                 if (expand)
174                                         break;
175                         } else {
176                                 /* other type of quote found */
177                                 if (start == NULL)
178                                         start = arg;
179                         }
180                         *arg++ = str[0];
181                         break;
182                 case ' ':
183                 case '\t':
184                 case '\n':
185                         if (inquote) {
186                                 if (start == NULL)
187                                         start = arg;
188                                 *arg++ = str[0];
189                                 break;
190                         }
191                         if (start == NULL)
192                                 break;
193                         /* FALLTHROUGH */
194                 case '\0':
195                         /*
196                          * end of a token -- make sure there's enough argv
197                          * space and save off a pointer.
198                          */
199                         if (aa->argc == aa->size) {
200                                 aa->size *= 2;          /* ramp up fast */
201                                 aa->argv = erealloc(aa->argv,
202                                     (aa->size + 1) * sizeof(char *));
203                         }
204
205                         *arg++ = '\0';
206                         if (start == NULL) {
207                                 aa->argv[aa->argc] = start;
208                                 return;
209                         }
210                         if (str[0] == '\n' || str[0] == '\0') {
211                                 aa->argv[aa->argc++] = start;
212                                 aa->argv[aa->argc] = NULL;
213                                 return;
214                         } else {
215                                 aa->argv[aa->argc++] = start;
216                                 start = NULL;
217                                 break;
218                         }
219                 case '\\':
220                         if (start == NULL)
221                                 start = arg;
222                         if (expand) {
223                                 switch (str[1]) {
224                                 case '\0':
225                                 case '\n':
226                                         /* hmmm; fix it up as best we can */
227                                         *arg++ = '\\';
228                                         break;
229                                 case 'b':
230                                         *arg++ = '\b';
231                                         ++str;
232                                         break;
233                                 case 'f':
234                                         *arg++ = '\f';
235                                         ++str;
236                                         break;
237                                 case 'n':
238                                         *arg++ = '\n';
239                                         ++str;
240                                         break;
241                                 case 'r':
242                                         *arg++ = '\r';
243                                         ++str;
244                                         break;
245                                 case 't':
246                                         *arg++ = '\t';
247                                         ++str;
248                                         break;
249                                 default:
250                                         *arg++ = str[1];
251                                         ++str;
252                                         break;
253                                 }
254                         } else {
255                                 *arg++ = str[0];
256                                 ++str;
257                                 *arg++ = str[0];
258                         }
259                         break;
260                 default:
261                         if (start == NULL)
262                                 start = arg;
263                         *arg++ = str[0];
264                         break;
265                 }
266                 ++str;
267         }
268 }
269
270 /*
271  * Quote a string for appending it to MAKEFLAGS. According to Posix the
272  * kind of quoting here is implementation-defined. This quoting must ensure
273  * that the parsing of MAKEFLAGS's contents in a sub-shell yields the same
274  * options, option arguments and macro definitions as in the calling make.
275  * We simply quote all blanks, which according to Posix are space and tab
276  * in the POSIX locale. Don't use isblank because in that case makes with
277  * different locale settings could not communicate. We must also quote
278  * backslashes obviously.
279  */
280 char *
281 MAKEFLAGS_quote(const char *str)
282 {
283         char *ret, *q;
284         const char *p;
285
286         /* assume worst case - everything has to be quoted */
287         ret = emalloc(strlen(str) * 2 + 1);
288
289         p = str;
290         q = ret;
291         while (*p != '\0') {
292                 switch (*p) {
293
294                   case ' ':
295                   case '\t':
296                         *q++ = '\\';
297                         break;
298
299                   default:
300                         break;
301                 }
302                 *q++ = *p++;
303         }
304         *q++ = '\0';
305         return (ret);
306 }
307
308 void
309 MAKEFLAGS_break(ArgArray *aa, const char str[])
310 {
311         char    *arg;
312         char    *start;
313
314         ArgArray_Init(aa);
315
316         aa->buffer = strdup(str);
317
318         arg = aa->buffer;
319         start = NULL;
320
321         for (;;) {
322                 switch (str[0]) {
323                 case ' ':
324                 case '\t':
325                         /* word separator */
326                         if (start == NULL) {
327                                 /* not in a word */
328                                 str++;
329                                 continue;
330                         }
331                         /* FALLTHRU */
332                 case '\0':
333                         if (aa->argc == aa->size) {
334                                 aa->size *= 2;
335                                 aa->argv = erealloc(aa->argv,
336                                     (aa->size + 1) * sizeof(char *));
337                         }
338
339                         *arg++ = '\0';
340                         if (start == NULL) {
341                                 aa->argv[aa->argc] = start;
342                                 return;
343                         }
344                         if (str[0] == '\0') {
345                                 aa->argv[aa->argc++] = start;
346                                 aa->argv[aa->argc] = NULL;
347                                 return;
348                         } else {
349                                 aa->argv[aa->argc++] = start;
350                                 start = NULL;
351                                 str++;
352                                 continue;
353                         }
354
355                 case '\\':
356                         if (str[1] == ' ' || str[1] == '\t')
357                                 str++;
358                         break;
359
360                 default:
361                         break;
362                 }
363                 if (start == NULL)
364                         start = arg;
365                 *arg++ = *str++;
366         }
367 }
368
369 /*
370  * Str_Match --
371  *
372  * See if a particular string matches a particular pattern.
373  *
374  * Results: Non-zero is returned if string matches pattern, 0 otherwise. The
375  * matching operation permits the following special characters in the
376  * pattern: *?\[] (see the man page for details on what these mean).
377  *
378  * Side effects: None.
379  */
380 int
381 Str_Match(const char *string, const char *pattern)
382 {
383         char c2;
384
385         for (;;) {
386                 /*
387                  * See if we're at the end of both the pattern and the
388                  * string. If, we succeeded.  If we're at the end of the
389                  * pattern but not at the end of the string, we failed.
390                  */
391                 if (*pattern == 0)
392                         return (!*string);
393                 if (*string == 0 && *pattern != '*')
394                         return (0);
395                 /*
396                  * Check for a "*" as the next pattern character.  It matches
397                  * any substring.  We handle this by calling ourselves
398                  * recursively for each postfix of string, until either we
399                  * match or we reach the end of the string.
400                  */
401                 if (*pattern == '*') {
402                         pattern += 1;
403                         if (*pattern == 0)
404                                 return (1);
405                         while (*string != 0) {
406                                 if (Str_Match(string, pattern))
407                                         return (1);
408                                 ++string;
409                         }
410                         return (0);
411                 }
412                 /*
413                  * Check for a "?" as the next pattern character.  It matches
414                  * any single character.
415                  */
416                 if (*pattern == '?')
417                         goto thisCharOK;
418                 /*
419                  * Check for a "[" as the next pattern character.  It is
420                  * followed by a list of characters that are acceptable, or
421                  * by a range (two characters separated by "-").
422                  */
423                 if (*pattern == '[') {
424                         ++pattern;
425                         for (;;) {
426                                 if ((*pattern == ']') || (*pattern == 0))
427                                         return (0);
428                                 if (*pattern == *string)
429                                         break;
430                                 if (pattern[1] == '-') {
431                                         c2 = pattern[2];
432                                         if (c2 == 0)
433                                                 return (0);
434                                         if ((*pattern <= *string) &&
435                                             (c2 >= *string))
436                                                 break;
437                                         if ((*pattern >= *string) &&
438                                             (c2 <= *string))
439                                                 break;
440                                         pattern += 2;
441                                 }
442                                 ++pattern;
443                         }
444                         while ((*pattern != ']') && (*pattern != 0))
445                                 ++pattern;
446                         goto thisCharOK;
447                 }
448                 /*
449                  * If the next pattern character is '/', just strip off the
450                  * '/' so we do exact matching on the character that follows.
451                  */
452                 if (*pattern == '\\') {
453                         ++pattern;
454                         if (*pattern == 0)
455                                 return (0);
456                 }
457                 /*
458                  * There's no special character.  Just make sure that the
459                  * next characters of each string match.
460                  */
461                 if (*pattern != *string)
462                         return (0);
463 thisCharOK:     ++pattern;
464                 ++string;
465         }
466 }
467
468
469 /**
470  * Str_SYSVMatch
471  *      Check word against pattern for a match (% is wild),
472  *
473  * Results:
474  *      Returns the beginning position of a match or null. The number
475  *      of characters matched is returned in len.
476  */
477 const char *
478 Str_SYSVMatch(const char *word, const char *pattern, int *len)
479 {
480         const char *m, *p, *w;
481
482         p = pattern;
483         w = word;
484
485         if (*w == '\0') {
486                 /* Zero-length word cannot be matched against */
487                 *len = 0;
488                 return (NULL);
489         }
490
491         if (*p == '\0') {
492                 /* Null pattern is the whole string */
493                 *len = strlen(w);
494                 return (w);
495         }
496
497         if ((m = strchr(p, '%')) != NULL) {
498                 /* check that the prefix matches */
499                 for (; p != m && *w && *w == *p; w++, p++)
500                         continue;
501
502                 if (p != m)
503                         return (NULL);  /* No match */
504
505                 if (*++p == '\0') {
506                         /* No more pattern, return the rest of the string */
507                         *len = strlen(w);
508                         return (w);
509                 }
510         }
511
512         m = w;
513
514         /* Find a matching tail */
515         do
516                 if (strcmp(p, w) == 0) {
517                         *len = w - m;
518                         return (m);
519                 }
520         while (*w++ != '\0');
521
522         return (NULL);
523 }
524
525
526 /**
527  * Str_SYSVSubst
528  *      Substitute '%' on the pattern with len characters from src.
529  *      If the pattern does not contain a '%' prepend len characters
530  *      from src.
531  *
532  * Side Effects:
533  *      Places result on buf
534  */
535 void
536 Str_SYSVSubst(Buffer *buf, const char *pat, const char *src, int len)
537 {
538         const char *m;
539
540         if ((m = strchr(pat, '%')) != NULL) {
541                 /* Copy the prefix */
542                 Buf_AppendRange(buf, pat, m);
543                 /* skip the % */
544                 pat = m + 1;
545         }
546
547         /* Copy the pattern */
548         Buf_AddBytes(buf, len, (const Byte *)src);
549
550         /* append the rest */
551         Buf_Append(buf, pat);
552 }
553