source: trunk/third/gmake/read.c @ 15972

Revision 15972, 74.3 KB checked in by ghudson, 24 years ago (diff)
This commit was generated by cvs2svn to compensate for changes in r15971, which included commits to RCS files with non-trunk default branches.
Line 
1/* Reading and parsing of makefiles for GNU Make.
2Copyright (C) 1988,89,90,91,92,93,94,95,96,97 Free Software Foundation, Inc.
3This file is part of GNU Make.
4
5GNU Make is free software; you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation; either version 2, or (at your option)
8any later version.
9
10GNU Make is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with GNU Make; see the file COPYING.  If not, write to
17the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18Boston, MA 02111-1307, USA.  */
19
20#include "make.h"
21
22#include <assert.h>
23
24#include <glob.h>
25
26#include "dep.h"
27#include "filedef.h"
28#include "job.h"
29#include "commands.h"
30#include "variable.h"
31#include "rule.h"
32#include "debug.h"
33
34
35#ifndef WINDOWS32
36#ifndef _AMIGA
37#ifndef VMS
38#include <pwd.h>
39#else
40struct passwd *getpwnam PARAMS ((char *name));
41#endif
42#endif
43#endif /* !WINDOWS32 */
44
45/* A `struct linebuffer' is a structure which holds a line of text.
46   `readline' reads a line from a stream into a linebuffer
47   and works regardless of the length of the line.  */
48
49struct linebuffer
50  {
51    /* Note:  This is the number of bytes malloc'ed for `buffer'
52       It does not indicate `buffer's real length.
53       Instead, a null char indicates end-of-string.  */
54    unsigned int size;
55    char *buffer;
56  };
57
58#define initbuffer(lb) (lb)->buffer = (char *) xmalloc ((lb)->size = 200)
59#define freebuffer(lb) free ((lb)->buffer)
60
61
62/* Types of "words" that can be read in a makefile.  */
63enum make_word_type
64  {
65     w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
66     w_comment, w_varassign
67  };
68
69
70/* A `struct conditionals' contains the information describing
71   all the active conditionals in a makefile.
72
73   The global variable `conditionals' contains the conditionals
74   information for the current makefile.  It is initialized from
75   the static structure `toplevel_conditionals' and is later changed
76   to new structures for included makefiles.  */
77
78struct conditionals
79  {
80    unsigned int if_cmds;       /* Depth of conditional nesting.  */
81    unsigned int allocated;     /* Elts allocated in following arrays.  */
82    char *ignoring;             /* Are we ignoring or interepreting?  */
83    char *seen_else;            /* Have we already seen an `else'?  */
84  };
85
86static struct conditionals toplevel_conditionals;
87static struct conditionals *conditionals = &toplevel_conditionals;
88
89
90/* Default directories to search for include files in  */
91
92static char *default_include_directories[] =
93  {
94#if defined(WINDOWS32) && !defined(INCLUDEDIR)
95/*
96 * This completly up to the user when they install MSVC or other packages.
97 * This is defined as a placeholder.
98 */
99#define INCLUDEDIR "."
100#endif
101    INCLUDEDIR,
102#ifndef _AMIGA
103    "/usr/gnu/include",
104    "/usr/local/include",
105    "/usr/include",
106#endif
107    0
108  };
109
110/* List of directories to search for include files in  */
111
112static char **include_directories;
113
114/* Maximum length of an element of the above.  */
115
116static unsigned int max_incl_len;
117
118/* The filename and pointer to line number of the
119   makefile currently being read in.  */
120
121const struct floc *reading_file;
122
123/* The chain of makefiles read by read_makefile.  */
124
125static struct dep *read_makefiles = 0;
126
127static int read_makefile PARAMS ((char *filename, int flags));
128static unsigned long readline PARAMS ((struct linebuffer *linebuffer,
129                                       FILE *stream, const struct floc *flocp));
130static void do_define PARAMS ((char *name, unsigned int namelen,
131                               enum variable_origin origin, FILE *infile,
132                               struct floc *flocp));
133static int conditional_line PARAMS ((char *line, const struct floc *flocp));
134static void record_files PARAMS ((struct nameseq *filenames, char *pattern, char *pattern_percent,
135                        struct dep *deps, unsigned int cmds_started, char *commands,
136                        unsigned int commands_idx, int two_colon,
137                        const struct floc *flocp, int set_default));
138static void record_target_var PARAMS ((struct nameseq *filenames, char *defn,
139                                       int two_colon,
140                                       enum variable_origin origin,
141                                       const struct floc *flocp));
142static enum make_word_type get_next_mword PARAMS ((char *buffer, char *delim,
143                        char **startp, unsigned int *length));
144
145/* Read in all the makefiles and return the chain of their names.  */
146
147struct dep *
148read_all_makefiles (makefiles)
149     char **makefiles;
150{
151  unsigned int num_makefiles = 0;
152
153  DB (DB_BASIC, (_("Reading makefiles...\n")));
154
155  /* If there's a non-null variable MAKEFILES, its value is a list of
156     files to read first thing.  But don't let it prevent reading the
157     default makefiles and don't let the default goal come from there.  */
158
159  {
160    char *value;
161    char *name, *p;
162    unsigned int length;
163
164    {
165      /* Turn off --warn-undefined-variables while we expand MAKEFILES.  */
166      int save = warn_undefined_variables_flag;
167      warn_undefined_variables_flag = 0;
168
169      value = allocated_variable_expand ("$(MAKEFILES)");
170
171      warn_undefined_variables_flag = save;
172    }
173
174    /* Set NAME to the start of next token and LENGTH to its length.
175       MAKEFILES is updated for finding remaining tokens.  */
176    p = value;
177
178    while ((name = find_next_token (&p, &length)) != 0)
179      {
180        if (*p != '\0')
181          *p++ = '\0';
182        name = xstrdup (name);
183        if (read_makefile (name,
184                           RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE) < 2)
185          free (name);
186      }
187
188    free (value);
189  }
190
191  /* Read makefiles specified with -f switches.  */
192
193  if (makefiles != 0)
194    while (*makefiles != 0)
195      {
196        struct dep *tail = read_makefiles;
197        register struct dep *d;
198
199        if (! read_makefile (*makefiles, 0))
200          perror_with_name ("", *makefiles);
201
202        /* Find the right element of read_makefiles.  */
203        d = read_makefiles;
204        while (d->next != tail)
205          d = d->next;
206
207        /* Use the storage read_makefile allocates.  */
208        *makefiles = dep_name (d);
209        ++num_makefiles;
210        ++makefiles;
211      }
212
213  /* If there were no -f switches, try the default names.  */
214
215  if (num_makefiles == 0)
216    {
217      static char *default_makefiles[] =
218#ifdef VMS
219        /* all lower case since readdir() (the vms version) 'lowercasifies' */
220        { "makefile.vms", "gnumakefile.", "makefile.", 0 };
221#else
222#ifdef _AMIGA
223        { "GNUmakefile", "Makefile", "SMakefile", 0 };
224#else /* !Amiga && !VMS */
225        { "GNUmakefile", "makefile", "Makefile", 0 };
226#endif /* AMIGA */
227#endif /* VMS */
228      register char **p = default_makefiles;
229      while (*p != 0 && !file_exists_p (*p))
230        ++p;
231
232      if (*p != 0)
233        {
234          if (! read_makefile (*p, 0))
235            perror_with_name ("", *p);
236        }
237      else
238        {
239          /* No default makefile was found.  Add the default makefiles to the
240             `read_makefiles' chain so they will be updated if possible.  */
241          struct dep *tail = read_makefiles;
242          /* Add them to the tail, after any MAKEFILES variable makefiles.  */
243          while (tail != 0 && tail->next != 0)
244            tail = tail->next;
245          for (p = default_makefiles; *p != 0; ++p)
246            {
247              struct dep *d = (struct dep *) xmalloc (sizeof (struct dep));
248              d->name = 0;
249              d->file = enter_file (*p);
250              d->file->dontcare = 1;
251              /* Tell update_goal_chain to bail out as soon as this file is
252                 made, and main not to die if we can't make this file.  */
253              d->changed = RM_DONTCARE;
254              if (tail == 0)
255                read_makefiles = d;
256              else
257                tail->next = d;
258              tail = d;
259            }
260          if (tail != 0)
261            tail->next = 0;
262        }
263    }
264
265  return read_makefiles;
266}
267
268/* Read file FILENAME as a makefile and add its contents to the data base.
269
270   FLAGS contains bits as above.
271
272   FILENAME is added to the `read_makefiles' chain.
273
274   Returns 0 if a file was not found or not read.
275   Returns 1 if FILENAME was found and read.
276   Returns 2 if FILENAME was read, and we kept a reference (don't free it).  */
277
278static int
279read_makefile (filename, flags)
280     char *filename;
281     int flags;
282{
283  static char *collapsed = 0;
284  static unsigned int collapsed_length = 0;
285  register FILE *infile;
286  struct linebuffer lb;
287  unsigned int commands_len = 200;
288  char *commands;
289  unsigned int commands_idx = 0;
290  unsigned int cmds_started, tgts_started;
291  char *p;
292  char *p2;
293  int len, reading_target;
294  int ignoring = 0, in_ignored_define = 0;
295  int no_targets = 0;           /* Set when reading a rule without targets.  */
296  struct floc fileinfo;
297  char *passed_filename = filename;
298
299  struct nameseq *filenames = 0;
300  struct dep *deps;
301  unsigned int nlines = 0;
302  int two_colon = 0;
303  char *pattern = 0, *pattern_percent;
304
305  int makefile_errno;
306#if defined (WINDOWS32) || defined (__MSDOS__)
307  int check_again;
308#endif
309
310#define record_waiting_files()                                                \
311  do                                                                          \
312    {                                                                         \
313      if (filenames != 0)                                                     \
314        {                                                                     \
315          struct floc fi;                                                     \
316          fi.filenm = fileinfo.filenm;                                        \
317          fi.lineno = tgts_started;                                           \
318          record_files (filenames, pattern, pattern_percent, deps,            \
319                        cmds_started, commands, commands_idx, two_colon,      \
320                        &fi, !(flags & RM_NO_DEFAULT_GOAL));                  \
321        }                                                                     \
322      filenames = 0;                                                          \
323      commands_idx = 0;                                                       \
324      if (pattern) { free(pattern); pattern = 0; }                            \
325    } while (0)
326
327  fileinfo.filenm = filename;
328  fileinfo.lineno = 1;
329
330  pattern_percent = 0;
331  cmds_started = tgts_started = fileinfo.lineno;
332
333  if (ISDB (DB_VERBOSE))
334    {
335      printf (_("Reading makefile `%s'"), fileinfo.filenm);
336      if (flags & RM_NO_DEFAULT_GOAL)
337        printf (_(" (no default goal)"));
338      if (flags & RM_INCLUDED)
339        printf (_(" (search path)"));
340      if (flags & RM_DONTCARE)
341        printf (_(" (don't care)"));
342      if (flags & RM_NO_TILDE)
343        printf (_(" (no ~ expansion)"));
344      puts ("...");
345    }
346
347  /* First, get a stream to read.  */
348
349  /* Expand ~ in FILENAME unless it came from `include',
350     in which case it was already done.  */
351  if (!(flags & RM_NO_TILDE) && filename[0] == '~')
352    {
353      char *expanded = tilde_expand (filename);
354      if (expanded != 0)
355        filename = expanded;
356    }
357
358  infile = fopen (filename, "r");
359  /* Save the error code so we print the right message later.  */
360  makefile_errno = errno;
361
362  /* If the makefile wasn't found and it's either a makefile from
363     the `MAKEFILES' variable or an included makefile,
364     search the included makefile search path for this makefile.  */
365  if (infile == 0 && (flags & RM_INCLUDED) && *filename != '/')
366    {
367      register unsigned int i;
368      for (i = 0; include_directories[i] != 0; ++i)
369        {
370          char *name = concat (include_directories[i], "/", filename);
371          infile = fopen (name, "r");
372          if (infile == 0)
373            free (name);
374          else
375            {
376              filename = name;
377              break;
378            }
379        }
380    }
381
382  /* Add FILENAME to the chain of read makefiles.  */
383  deps = (struct dep *) xmalloc (sizeof (struct dep));
384  deps->next = read_makefiles;
385  read_makefiles = deps;
386  deps->name = 0;
387  deps->file = lookup_file (filename);
388  if (deps->file == 0)
389    {
390      deps->file = enter_file (xstrdup (filename));
391      if (flags & RM_DONTCARE)
392        deps->file->dontcare = 1;
393    }
394  if (filename != passed_filename)
395    free (filename);
396  filename = deps->file->name;
397  deps->changed = flags;
398  deps = 0;
399
400  /* If the makefile can't be found at all, give up entirely.  */
401
402  if (infile == 0)
403    {
404      /* If we did some searching, errno has the error from the last
405         attempt, rather from FILENAME itself.  Restore it in case the
406         caller wants to use it in a message.  */
407      errno = makefile_errno;
408      return 0;
409    }
410
411  reading_file = &fileinfo;
412
413  /* Loop over lines in the file.
414     The strategy is to accumulate target names in FILENAMES, dependencies
415     in DEPS and commands in COMMANDS.  These are used to define a rule
416     when the start of the next rule (or eof) is encountered.  */
417
418  initbuffer (&lb);
419  commands = xmalloc (200);
420
421  while (!feof (infile))
422    {
423      fileinfo.lineno += nlines;
424      nlines = readline (&lb, infile, &fileinfo);
425
426      /* Check for a shell command line first.
427         If it is not one, we can stop treating tab specially.  */
428      if (lb.buffer[0] == '\t')
429        {
430          /* This line is a probably shell command.  */
431          unsigned int len;
432
433          if (no_targets)
434            /* Ignore the commands in a rule with no targets.  */
435            continue;
436
437          /* If there is no preceding rule line, don't treat this line
438             as a command, even though it begins with a tab character.
439             SunOS 4 make appears to behave this way.  */
440
441          if (filenames != 0)
442            {
443              if (ignoring)
444                /* Yep, this is a shell command, and we don't care.  */
445                continue;
446
447              /* Append this command line to the line being accumulated.  */
448              p = lb.buffer;
449              if (commands_idx == 0)
450                cmds_started = fileinfo.lineno;
451              len = strlen (p);
452              if (len + 1 + commands_idx > commands_len)
453                {
454                  commands_len = (len + 1 + commands_idx) * 2;
455                  commands = (char *) xrealloc (commands, commands_len);
456                }
457              bcopy (p, &commands[commands_idx], len);
458              commands_idx += len;
459              commands[commands_idx++] = '\n';
460
461              continue;
462            }
463        }
464
465      /* This line is not a shell command line.  Don't worry about tabs.  */
466
467      if (collapsed_length < lb.size)
468        {
469          collapsed_length = lb.size;
470          if (collapsed != 0)
471            free (collapsed);
472          collapsed = (char *) xmalloc (collapsed_length);
473        }
474      strcpy (collapsed, lb.buffer);
475      /* Collapse continuation lines.  */
476      collapse_continuations (collapsed);
477      remove_comments (collapsed);
478
479      /* Compare a word, both length and contents. */
480#define word1eq(s, l)   (len == l && strneq (s, p, l))
481      p = collapsed;
482      while (isspace ((unsigned char)*p))
483        ++p;
484      if (*p == '\0')
485        /* This line is completely empty.  */
486        continue;
487
488      /* Find the end of the first token.  Note we don't need to worry about
489       * ":" here since we compare tokens by length (so "export" will never
490       * be equal to "export:").
491       */
492      for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
493        {}
494      len = p2 - p;
495
496      /* Find the start of the second token.  If it's a `:' remember it,
497         since it can't be a preprocessor token--this allows targets named
498         `ifdef', `export', etc. */
499      reading_target = 0;
500      while (isspace ((unsigned char)*p2))
501        ++p2;
502      if (*p2 == '\0')
503        p2 = NULL;
504      else if (p2[0] == ':' && p2[1] == '\0')
505        {
506          reading_target = 1;
507          goto skip_conditionals;
508        }
509
510      /* We must first check for conditional and `define' directives before
511         ignoring anything, since they control what we will do with
512         following lines.  */
513
514      if (!in_ignored_define
515          && (word1eq ("ifdef", 5) || word1eq ("ifndef", 6)
516              || word1eq ("ifeq", 4) || word1eq ("ifneq", 5)
517              || word1eq ("else", 4) || word1eq ("endif", 5)))
518        {
519          int i = conditional_line (p, &fileinfo);
520          if (i >= 0)
521            ignoring = i;
522          else
523            fatal (&fileinfo, _("invalid syntax in conditional"));
524          continue;
525        }
526
527      if (word1eq ("endef", 5))
528        {
529          if (in_ignored_define)
530            in_ignored_define = 0;
531          else
532            fatal (&fileinfo, _("extraneous `endef'"));
533          continue;
534        }
535
536      if (word1eq ("define", 6))
537        {
538          if (ignoring)
539            in_ignored_define = 1;
540          else
541            {
542              p2 = next_token (p + 6);
543              if (*p2 == '\0')
544                fatal (&fileinfo, _("empty variable name"));
545
546              /* Let the variable name be the whole rest of the line,
547                 with trailing blanks stripped (comments have already been
548                 removed), so it could be a complex variable/function
549                 reference that might contain blanks.  */
550              p = strchr (p2, '\0');
551              while (isblank ((unsigned char)p[-1]))
552                --p;
553              do_define (p2, p - p2, o_file, infile, &fileinfo);
554            }
555          continue;
556        }
557
558      if (word1eq ("override", 8))
559        {
560          p2 = next_token (p + 8);
561          if (*p2 == '\0')
562            error (&fileinfo, _("empty `override' directive"));
563          if (strneq (p2, "define", 6)
564              && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
565            {
566              if (ignoring)
567                in_ignored_define = 1;
568              else
569                {
570                  p2 = next_token (p2 + 6);
571                  if (*p2 == '\0')
572                    fatal (&fileinfo, _("empty variable name"));
573
574                  /* Let the variable name be the whole rest of the line,
575                     with trailing blanks stripped (comments have already been
576                     removed), so it could be a complex variable/function
577                     reference that might contain blanks.  */
578                  p = strchr (p2, '\0');
579                  while (isblank ((unsigned char)p[-1]))
580                    --p;
581                  do_define (p2, p - p2, o_override, infile, &fileinfo);
582                }
583            }
584          else if (!ignoring
585                   && !try_variable_definition (&fileinfo, p2, o_override, 0))
586            error (&fileinfo, _("invalid `override' directive"));
587
588          continue;
589        }
590 skip_conditionals:
591
592      if (ignoring)
593        /* Ignore the line.  We continue here so conditionals
594           can appear in the middle of a rule.  */
595        continue;
596
597      if (!reading_target && word1eq ("export", 6))
598        {
599          struct variable *v;
600          p2 = next_token (p + 6);
601          if (*p2 == '\0')
602            export_all_variables = 1;
603          v = try_variable_definition (&fileinfo, p2, o_file, 0);
604          if (v != 0)
605            v->export = v_export;
606          else
607            {
608              unsigned int len;
609              for (p = find_next_token (&p2, &len); p != 0;
610                   p = find_next_token (&p2, &len))
611                {
612                  v = lookup_variable (p, len);
613                  if (v == 0)
614                    v = define_variable_loc (p, len, "", o_file, 0, &fileinfo);
615                  v->export = v_export;
616                }
617            }
618        }
619      else if (!reading_target && word1eq ("unexport", 8))
620        {
621          unsigned int len;
622          struct variable *v;
623          p2 = next_token (p + 8);
624          if (*p2 == '\0')
625            export_all_variables = 0;
626          for (p = find_next_token (&p2, &len); p != 0;
627               p = find_next_token (&p2, &len))
628            {
629              v = lookup_variable (p, len);
630              if (v == 0)
631                v = define_variable_loc (p, len, "", o_file, 0, &fileinfo);
632              v->export = v_noexport;
633            }
634        }
635      else if (word1eq ("vpath", 5))
636        {
637          char *pattern;
638          unsigned int len;
639          p2 = variable_expand (p + 5);
640          p = find_next_token (&p2, &len);
641          if (p != 0)
642            {
643              pattern = savestring (p, len);
644              p = find_next_token (&p2, &len);
645              /* No searchpath means remove all previous
646                 selective VPATH's with the same pattern.  */
647            }
648          else
649            /* No pattern means remove all previous selective VPATH's.  */
650            pattern = 0;
651          construct_vpath_list (pattern, p);
652          if (pattern != 0)
653            free (pattern);
654        }
655      else if (word1eq ("include", 7) || word1eq ("-include", 8)
656               || word1eq ("sinclude", 8))
657        {
658          /* We have found an `include' line specifying a nested
659             makefile to be read at this point.  */
660          struct conditionals *save, new_conditionals;
661          struct nameseq *files;
662          /* "-include" (vs "include") says no error if the file does not
663             exist.  "sinclude" is an alias for this from SGI.  */
664          int noerror = p[0] != 'i';
665
666          p = allocated_variable_expand (next_token (p + (noerror ? 8 : 7)));
667          if (*p == '\0')
668            {
669              error (&fileinfo,
670                     _("no file name for `%sinclude'"), noerror ? "-" : "");
671              continue;
672            }
673
674          /* Parse the list of file names.  */
675          p2 = p;
676          files = multi_glob (parse_file_seq (&p2, '\0',
677                                              sizeof (struct nameseq),
678                                              1),
679                              sizeof (struct nameseq));
680          free (p);
681
682          /* Save the state of conditionals and start
683             the included makefile with a clean slate.  */
684          save = conditionals;
685          bzero ((char *) &new_conditionals, sizeof new_conditionals);
686          conditionals = &new_conditionals;
687
688          /* Record the rules that are waiting so they will determine
689             the default goal before those in the included makefile.  */
690          record_waiting_files ();
691
692          /* Read each included makefile.  */
693          while (files != 0)
694            {
695              struct nameseq *next = files->next;
696              char *name = files->name;
697              int r;
698
699              free ((char *)files);
700              files = next;
701
702              r = read_makefile (name, (RM_INCLUDED | RM_NO_TILDE
703                                        | (noerror ? RM_DONTCARE : 0)));
704              if (!r)
705                {
706                  if (!noerror)
707                    error (&fileinfo, "%s: %s", name, strerror (errno));
708                  free (name);
709                }
710            }
711
712          /* Free any space allocated by conditional_line.  */
713          if (conditionals->ignoring)
714            free (conditionals->ignoring);
715          if (conditionals->seen_else)
716            free (conditionals->seen_else);
717
718          /* Restore state.  */
719          conditionals = save;
720          reading_file = &fileinfo;
721        }
722#undef  word1eq
723      else if (try_variable_definition (&fileinfo, p, o_file, 0))
724        /* This line has been dealt with.  */
725        ;
726      else if (lb.buffer[0] == '\t')
727        {
728          p = collapsed;        /* Ignore comments.  */
729          while (isblank ((unsigned char)*p))
730            ++p;
731          if (*p == '\0')
732            /* The line is completely blank; that is harmless.  */
733            continue;
734          /* This line starts with a tab but was not caught above
735             because there was no preceding target, and the line
736             might have been usable as a variable definition.
737             But now it is definitely lossage.  */
738          fatal(&fileinfo, _("commands commence before first target"));
739        }
740      else
741        {
742          /* This line describes some target files.  This is complicated by
743             the existence of target-specific variables, because we can't
744             expand the entire line until we know if we have one or not.  So
745             we expand the line word by word until we find the first `:',
746             then check to see if it's a target-specific variable.
747
748             In this algorithm, `lb_next' will point to the beginning of the
749             unexpanded parts of the input buffer, while `p2' points to the
750             parts of the expanded buffer we haven't searched yet. */
751
752          enum make_word_type wtype;
753          enum variable_origin v_origin;
754          char *cmdleft, *semip, *lb_next;
755          unsigned int len, plen = 0;
756          char *colonp;
757
758          /* Record the previous rule.  */
759
760          record_waiting_files ();
761          tgts_started = fileinfo.lineno;
762
763          /* Search the line for an unquoted ; that is not after an
764             unquoted #.  */
765          cmdleft = find_char_unquote (lb.buffer, ";#", 0);
766          if (cmdleft != 0 && *cmdleft == '#')
767            {
768              /* We found a comment before a semicolon.  */
769              *cmdleft = '\0';
770              cmdleft = 0;
771            }
772          else if (cmdleft != 0)
773            /* Found one.  Cut the line short there before expanding it.  */
774            *(cmdleft++) = '\0';
775          semip = cmdleft;
776
777          collapse_continuations (lb.buffer);
778
779          /* We can't expand the entire line, since if it's a per-target
780             variable we don't want to expand it.  So, walk from the
781             beginning, expanding as we go, and looking for "interesting"
782             chars.  The first word is always expandable.  */
783          wtype = get_next_mword(lb.buffer, NULL, &lb_next, &len);
784          switch (wtype)
785            {
786            case w_eol:
787              if (cmdleft != 0)
788                fatal(&fileinfo, _("missing rule before commands"));
789              /* This line contained something but turned out to be nothing
790                 but whitespace (a comment?).  */
791              continue;
792
793            case w_colon:
794            case w_dcolon:
795              /* We accept and ignore rules without targets for
796                 compatibility with SunOS 4 make.  */
797              no_targets = 1;
798              continue;
799
800            default:
801              break;
802            }
803
804          p2 = variable_expand_string(NULL, lb_next, len);
805          while (1)
806            {
807              lb_next += len;
808              if (cmdleft == 0)
809                {
810                  /* Look for a semicolon in the expanded line.  */
811                  cmdleft = find_char_unquote (p2, ";", 0);
812
813                  if (cmdleft != 0)
814                    {
815                      unsigned long p2_off = p2 - variable_buffer;
816                      unsigned long cmd_off = cmdleft - variable_buffer;
817                      char *pend = p2 + strlen(p2);
818
819                      /* Append any remnants of lb, then cut the line short
820                         at the semicolon.  */
821                      *cmdleft = '\0';
822
823                      /* One school of thought says that you shouldn't expand
824                         here, but merely copy, since now you're beyond a ";"
825                         and into a command script.  However, the old parser
826                         expanded the whole line, so we continue that for
827                         backwards-compatiblity.  Also, it wouldn't be
828                         entirely consistent, since we do an unconditional
829                         expand below once we know we don't have a
830                         target-specific variable. */
831                      (void)variable_expand_string(pend, lb_next, (long)-1);
832                      lb_next += strlen(lb_next);
833                      p2 = variable_buffer + p2_off;
834                      cmdleft = variable_buffer + cmd_off + 1;
835                    }
836                }
837
838              colonp = find_char_unquote(p2, ":", 0);
839#if defined(__MSDOS__) || defined(WINDOWS32)
840              /* The drive spec brain-damage strikes again...  */
841              /* Note that the only separators of targets in this context
842                 are whitespace and a left paren.  If others are possible,
843                 they should be added to the string in the call to index.  */
844              while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
845                     colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
846                     (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
847                colonp = find_char_unquote(colonp + 1, ":", 0);
848#endif
849              if (colonp != 0)
850                break;
851
852              wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
853              if (wtype == w_eol)
854                break;
855
856              p2 += strlen(p2);
857              *(p2++) = ' ';
858              p2 = variable_expand_string(p2, lb_next, len);
859              /* We don't need to worry about cmdleft here, because if it was
860                 found in the variable_buffer the entire buffer has already
861                 been expanded... we'll never get here.  */
862            }
863
864          p2 = next_token (variable_buffer);
865
866          /* If the word we're looking at is EOL, see if there's _anything_
867             on the line.  If not, a variable expanded to nothing, so ignore
868             it.  If so, we can't parse this line so punt.  */
869          if (wtype == w_eol)
870            {
871              if (*p2 != '\0')
872                /* There's no need to be ivory-tower about this: check for
873                   one of the most common bugs found in makefiles...  */
874                fatal (&fileinfo, _("missing separator%s"),
875                       !strneq(lb.buffer, "        ", 8) ? ""
876                       : _(" (did you mean TAB instead of 8 spaces?)"));
877              continue;
878            }
879
880          /* Make the colon the end-of-string so we know where to stop
881             looking for targets.  */
882          *colonp = '\0';
883          filenames = multi_glob (parse_file_seq (&p2, '\0',
884                                                  sizeof (struct nameseq),
885                                                  1),
886                                  sizeof (struct nameseq));
887          *p2 = ':';
888
889          if (!filenames)
890            {
891              /* We accept and ignore rules without targets for
892                 compatibility with SunOS 4 make.  */
893              no_targets = 1;
894              continue;
895            }
896          /* This should never be possible; we handled it above.  */
897          assert (*p2 != '\0');
898          ++p2;
899
900          /* Is this a one-colon or two-colon entry?  */
901          two_colon = *p2 == ':';
902          if (two_colon)
903            p2++;
904
905          /* Test to see if it's a target-specific variable.  Copy the rest
906             of the buffer over, possibly temporarily (we'll expand it later
907             if it's not a target-specific variable).  PLEN saves the length
908             of the unparsed section of p2, for later.  */
909          if (*lb_next != '\0')
910            {
911              unsigned int l = p2 - variable_buffer;
912              plen = strlen (p2);
913              (void) variable_buffer_output (p2+plen,
914                                             lb_next, strlen (lb_next)+1);
915              p2 = variable_buffer + l;
916            }
917
918          /* See if it's an "override" keyword; if so see if what comes after
919             it looks like a variable definition.  */
920
921          wtype = get_next_mword (p2, NULL, &p, &len);
922
923          v_origin = o_file;
924          if (wtype == w_static && (len == (sizeof ("override")-1)
925                                    && strneq (p, "override", len)))
926            {
927              v_origin = o_override;
928              wtype = get_next_mword (p+len, NULL, &p, &len);
929            }
930
931          if (wtype != w_eol)
932            wtype = get_next_mword (p+len, NULL, NULL, NULL);
933
934          if (wtype == w_varassign)
935            {
936              /* If there was a semicolon found, add it back, plus anything
937                 after it.  */
938              if (semip)
939                {
940                  *(--semip) = ';';
941                  variable_buffer_output (p2 + strlen (p2),
942                                          semip, strlen (semip)+1);
943                }
944              record_target_var (filenames, p, two_colon, v_origin, &fileinfo);
945              filenames = 0;
946              continue;
947            }
948
949          /* This is a normal target, _not_ a target-specific variable.
950             Unquote any = in the dependency list.  */
951          find_char_unquote (lb_next, "=", 0);
952
953          /* We have some targets, so don't ignore the following commands.  */
954          no_targets = 0;
955
956          /* Expand the dependencies, etc.  */
957          if (*lb_next != '\0')
958            {
959              unsigned int l = p2 - variable_buffer;
960              (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
961              p2 = variable_buffer + l;
962
963              /* Look for a semicolon in the expanded line.  */
964              if (cmdleft == 0)
965                {
966                  cmdleft = find_char_unquote (p2, ";", 0);
967                  if (cmdleft != 0)
968                    *(cmdleft++) = '\0';
969                }
970            }
971
972          /* Is this a static pattern rule: `target: %targ: %dep; ...'?  */
973          p = strchr (p2, ':');
974          while (p != 0 && p[-1] == '\\')
975            {
976              register char *q = &p[-1];
977              register int backslash = 0;
978              while (*q-- == '\\')
979                backslash = !backslash;
980              if (backslash)
981                p = strchr (p + 1, ':');
982              else
983                break;
984            }
985#ifdef _AMIGA
986          /* Here, the situation is quite complicated. Let's have a look
987            at a couple of targets:
988
989                install: dev:make
990
991                dev:make: make
992
993                dev:make:: xyz
994
995            The rule is that it's only a target, if there are TWO :'s
996            OR a space around the :.
997          */
998          if (p && !(isspace ((unsigned char)p[1]) || !p[1]
999                     || isspace ((unsigned char)p[-1])))
1000            p = 0;
1001#endif
1002#if defined (WINDOWS32) || defined (__MSDOS__)
1003          do {
1004            check_again = 0;
1005            /* For MSDOS and WINDOWS32, skip a "C:\..." or a "C:/..." */
1006            if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1007                isalpha ((unsigned char)p[-1]) &&
1008                (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1009              p = strchr (p + 1, ':');
1010              check_again = 1;
1011            }
1012          } while (check_again);
1013#endif
1014          if (p != 0)
1015            {
1016              struct nameseq *target;
1017              target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1018              ++p2;
1019              if (target == 0)
1020                fatal (&fileinfo, _("missing target pattern"));
1021              else if (target->next != 0)
1022                fatal (&fileinfo, _("multiple target patterns"));
1023              pattern = target->name;
1024              pattern_percent = find_percent (pattern);
1025              if (pattern_percent == 0)
1026                fatal (&fileinfo, _("target pattern contains no `%%'"));
1027              free((char *)target);
1028            }
1029          else
1030            pattern = 0;
1031
1032          /* Parse the dependencies.  */
1033          deps = (struct dep *)
1034            multi_glob (parse_file_seq (&p2, '\0', sizeof (struct dep), 1),
1035                        sizeof (struct dep));
1036
1037          commands_idx = 0;
1038          if (cmdleft != 0)
1039            {
1040              /* Semicolon means rest of line is a command.  */
1041              unsigned int len = strlen (cmdleft);
1042
1043              cmds_started = fileinfo.lineno;
1044
1045              /* Add this command line to the buffer.  */
1046              if (len + 2 > commands_len)
1047                {
1048                  commands_len = (len + 2) * 2;
1049                  commands = (char *) xrealloc (commands, commands_len);
1050                }
1051              bcopy (cmdleft, commands, len);
1052              commands_idx += len;
1053              commands[commands_idx++] = '\n';
1054            }
1055
1056          continue;
1057        }
1058
1059      /* We get here except in the case that we just read a rule line.
1060         Record now the last rule we read, so following spurious
1061         commands are properly diagnosed.  */
1062      record_waiting_files ();
1063      no_targets = 0;
1064    }
1065
1066  if (conditionals->if_cmds)
1067    fatal (&fileinfo, _("missing `endif'"));
1068
1069  /* At eof, record the last rule.  */
1070  record_waiting_files ();
1071
1072  freebuffer (&lb);
1073  free ((char *) commands);
1074  fclose (infile);
1075
1076  reading_file = 0;
1077
1078  return 1;
1079}
1080
1081/* Execute a `define' directive.
1082   The first line has already been read, and NAME is the name of
1083   the variable to be defined.  The following lines remain to be read.
1084   LINENO, INFILE and FILENAME refer to the makefile being read.
1085   The value returned is LINENO, updated for lines read here.  */
1086
1087static void
1088do_define (name, namelen, origin, infile, flocp)
1089     char *name;
1090     unsigned int namelen;
1091     enum variable_origin origin;
1092     FILE *infile;
1093     struct floc *flocp;
1094{
1095  struct linebuffer lb;
1096  unsigned int nlines = 0;
1097  unsigned int length = 100;
1098  char *definition = (char *) xmalloc (100);
1099  register unsigned int idx = 0;
1100  register char *p;
1101
1102  /* Expand the variable name.  */
1103  char *var = (char *) alloca (namelen + 1);
1104  bcopy (name, var, namelen);
1105  var[namelen] = '\0';
1106  var = variable_expand (var);
1107
1108  initbuffer (&lb);
1109  while (!feof (infile))
1110    {
1111      unsigned int len;
1112
1113      flocp->lineno += nlines;
1114      nlines = readline (&lb, infile, flocp);
1115
1116      collapse_continuations (lb.buffer);
1117
1118      p = next_token (lb.buffer);
1119      len = strlen (p);
1120      if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1121          && strneq (p, "endef", 5))
1122        {
1123          p += 5;
1124          remove_comments (p);
1125          if (*next_token (p) != '\0')
1126            error (flocp, _("Extraneous text after `endef' directive"));
1127          /* Define the variable.  */
1128          if (idx == 0)
1129            definition[0] = '\0';
1130          else
1131            definition[idx - 1] = '\0';
1132          (void) define_variable_loc (var, strlen (var), definition, origin,
1133                                      1, flocp);
1134          free (definition);
1135          freebuffer (&lb);
1136          return;
1137        }
1138      else
1139        {
1140          len = strlen (lb.buffer);
1141          /* Increase the buffer size if necessary.  */
1142          if (idx + len + 1 > length)
1143            {
1144              length = (idx + len) * 2;
1145              definition = (char *) xrealloc (definition, length + 1);
1146            }
1147
1148          bcopy (lb.buffer, &definition[idx], len);
1149          idx += len;
1150          /* Separate lines with a newline.  */
1151          definition[idx++] = '\n';
1152        }
1153    }
1154
1155  /* No `endef'!!  */
1156  fatal (flocp, _("missing `endef', unterminated `define'"));
1157
1158  /* NOTREACHED */
1159  return;
1160}
1161
1162/* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1163   "ifneq", "else" and "endif".
1164   LINE is the input line, with the command as its first word.
1165
1166   FILENAME and LINENO are the filename and line number in the
1167   current makefile.  They are used for error messages.
1168
1169   Value is -1 if the line is invalid,
1170   0 if following text should be interpreted,
1171   1 if following text should be ignored.  */
1172
1173static int
1174conditional_line (line, flocp)
1175     char *line;
1176     const struct floc *flocp;
1177{
1178  int notdef;
1179  char *cmdname;
1180  register unsigned int i;
1181
1182  if (*line == 'i')
1183    {
1184      /* It's an "if..." command.  */
1185      notdef = line[2] == 'n';
1186      if (notdef)
1187        {
1188          cmdname = line[3] == 'd' ? "ifndef" : "ifneq";
1189          line += cmdname[3] == 'd' ? 7 : 6;
1190        }
1191      else
1192        {
1193          cmdname = line[2] == 'd' ? "ifdef" : "ifeq";
1194          line += cmdname[2] == 'd' ? 6 : 5;
1195        }
1196    }
1197  else
1198    {
1199      /* It's an "else" or "endif" command.  */
1200      notdef = line[1] == 'n';
1201      cmdname = notdef ? "endif" : "else";
1202      line += notdef ? 5 : 4;
1203    }
1204
1205  line = next_token (line);
1206
1207  if (*cmdname == 'e')
1208    {
1209      if (*line != '\0')
1210        error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1211      /* "Else" or "endif".  */
1212      if (conditionals->if_cmds == 0)
1213        fatal (flocp, _("extraneous `%s'"), cmdname);
1214      /* NOTDEF indicates an `endif' command.  */
1215      if (notdef)
1216        --conditionals->if_cmds;
1217      else if (conditionals->seen_else[conditionals->if_cmds - 1])
1218        fatal (flocp, _("only one `else' per conditional"));
1219      else
1220        {
1221          /* Toggle the state of ignorance.  */
1222          conditionals->ignoring[conditionals->if_cmds - 1]
1223            = !conditionals->ignoring[conditionals->if_cmds - 1];
1224          /* Record that we have seen an `else' in this conditional.
1225             A second `else' will be erroneous.  */
1226          conditionals->seen_else[conditionals->if_cmds - 1] = 1;
1227        }
1228      for (i = 0; i < conditionals->if_cmds; ++i)
1229        if (conditionals->ignoring[i])
1230          return 1;
1231      return 0;
1232    }
1233
1234  if (conditionals->allocated == 0)
1235    {
1236      conditionals->allocated = 5;
1237      conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1238      conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1239    }
1240
1241  ++conditionals->if_cmds;
1242  if (conditionals->if_cmds > conditionals->allocated)
1243    {
1244      conditionals->allocated += 5;
1245      conditionals->ignoring = (char *)
1246        xrealloc (conditionals->ignoring, conditionals->allocated);
1247      conditionals->seen_else = (char *)
1248        xrealloc (conditionals->seen_else, conditionals->allocated);
1249    }
1250
1251  /* Record that we have seen an `if...' but no `else' so far.  */
1252  conditionals->seen_else[conditionals->if_cmds - 1] = 0;
1253
1254  /* Search through the stack to see if we're already ignoring.  */
1255  for (i = 0; i < conditionals->if_cmds - 1; ++i)
1256    if (conditionals->ignoring[i])
1257      {
1258        /* We are already ignoring, so just push a level
1259           to match the next "else" or "endif", and keep ignoring.
1260           We don't want to expand variables in the condition.  */
1261        conditionals->ignoring[conditionals->if_cmds - 1] = 1;
1262        return 1;
1263      }
1264
1265  if (cmdname[notdef ? 3 : 2] == 'd')
1266    {
1267      /* "Ifdef" or "ifndef".  */
1268      struct variable *v;
1269      register char *p = end_of_token (line);
1270      i = p - line;
1271      p = next_token (p);
1272      if (*p != '\0')
1273        return -1;
1274      v = lookup_variable (line, i);
1275      conditionals->ignoring[conditionals->if_cmds - 1]
1276        = (v != 0 && *v->value != '\0') == notdef;
1277    }
1278  else
1279    {
1280      /* "Ifeq" or "ifneq".  */
1281      char *s1, *s2;
1282      unsigned int len;
1283      char termin = *line == '(' ? ',' : *line;
1284
1285      if (termin != ',' && termin != '"' && termin != '\'')
1286        return -1;
1287
1288      s1 = ++line;
1289      /* Find the end of the first string.  */
1290      if (termin == ',')
1291        {
1292          register int count = 0;
1293          for (; *line != '\0'; ++line)
1294            if (*line == '(')
1295              ++count;
1296            else if (*line == ')')
1297              --count;
1298            else if (*line == ',' && count <= 0)
1299              break;
1300        }
1301      else
1302        while (*line != '\0' && *line != termin)
1303          ++line;
1304
1305      if (*line == '\0')
1306        return -1;
1307
1308      if (termin == ',')
1309        {
1310          /* Strip blanks after the first string.  */
1311          char *p = line++;
1312          while (isblank ((unsigned char)p[-1]))
1313            --p;
1314          *p = '\0';
1315        }
1316      else
1317        *line++ = '\0';
1318
1319      s2 = variable_expand (s1);
1320      /* We must allocate a new copy of the expanded string because
1321         variable_expand re-uses the same buffer.  */
1322      len = strlen (s2);
1323      s1 = (char *) alloca (len + 1);
1324      bcopy (s2, s1, len + 1);
1325
1326      if (termin != ',')
1327        /* Find the start of the second string.  */
1328        line = next_token (line);
1329
1330      termin = termin == ',' ? ')' : *line;
1331      if (termin != ')' && termin != '"' && termin != '\'')
1332        return -1;
1333
1334      /* Find the end of the second string.  */
1335      if (termin == ')')
1336        {
1337          register int count = 0;
1338          s2 = next_token (line);
1339          for (line = s2; *line != '\0'; ++line)
1340            {
1341              if (*line == '(')
1342                ++count;
1343              else if (*line == ')')
1344                {
1345                  if (count <= 0)
1346                    break;
1347                  else
1348                    --count;
1349                }
1350            }
1351        }
1352      else
1353        {
1354          ++line;
1355          s2 = line;
1356          while (*line != '\0' && *line != termin)
1357            ++line;
1358        }
1359
1360      if (*line == '\0')
1361        return -1;
1362
1363      *line = '\0';
1364      line = next_token (++line);
1365      if (*line != '\0')
1366        error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1367
1368      s2 = variable_expand (s2);
1369      conditionals->ignoring[conditionals->if_cmds - 1]
1370        = streq (s1, s2) == notdef;
1371    }
1372
1373  /* Search through the stack to see if we're ignoring.  */
1374  for (i = 0; i < conditionals->if_cmds; ++i)
1375    if (conditionals->ignoring[i])
1376      return 1;
1377  return 0;
1378}
1379
1380/* Remove duplicate dependencies in CHAIN.  */
1381
1382void
1383uniquize_deps (chain)
1384     struct dep *chain;
1385{
1386  register struct dep *d;
1387
1388  /* Make sure that no dependencies are repeated.  This does not
1389     really matter for the purpose of updating targets, but it
1390     might make some names be listed twice for $^ and $?.  */
1391
1392  for (d = chain; d != 0; d = d->next)
1393    {
1394      struct dep *last, *next;
1395
1396      last = d;
1397      next = d->next;
1398      while (next != 0)
1399        if (streq (dep_name (d), dep_name (next)))
1400          {
1401            struct dep *n = next->next;
1402            last->next = n;
1403            if (next->name != 0 && next->name != d->name)
1404              free (next->name);
1405            if (next != d)
1406              free ((char *) next);
1407            next = n;
1408          }
1409        else
1410          {
1411            last = next;
1412            next = next->next;
1413          }
1414    }
1415}
1416
1417/* Record target-specific variable values for files FILENAMES.
1418   TWO_COLON is nonzero if a double colon was used.
1419
1420   The links of FILENAMES are freed, and so are any names in it
1421   that are not incorporated into other data structures.
1422
1423   If the target is a pattern, add the variable to the pattern-specific
1424   variable value list.  */
1425
1426static void
1427record_target_var (filenames, defn, two_colon, origin, flocp)
1428     struct nameseq *filenames;
1429     char *defn;
1430     int two_colon;
1431     enum variable_origin origin;
1432     const struct floc *flocp;
1433{
1434  struct nameseq *nextf;
1435  struct variable_set_list *global;
1436
1437  global = current_variable_set_list;
1438
1439  /* If the variable is an append version, store that but treat it as a
1440     normal recursive variable.  */
1441
1442  for (; filenames != 0; filenames = nextf)
1443    {
1444      struct variable *v;
1445      register char *name = filenames->name;
1446      struct variable_set_list *vlist;
1447      char *fname;
1448      char *percent;
1449
1450      nextf = filenames->next;
1451      free ((char *) filenames);
1452
1453      /* If it's a pattern target, then add it to the pattern-specific
1454         variable list.  */
1455      percent = find_percent (name);
1456      if (percent)
1457        {
1458          struct pattern_var *p;
1459
1460          /* Get a reference for this pattern-specific variable struct.  */
1461          p = create_pattern_var(name, percent);
1462          vlist = p->vars;
1463          fname = p->target;
1464        }
1465      else
1466        {
1467          struct file *f;
1468
1469          /* Get a file reference for this file, and initialize it.  */
1470          f = enter_file (name);
1471          initialize_file_variables (f, 1);
1472          vlist = f->variables;
1473          fname = f->name;
1474        }
1475
1476      /* Make the new variable context current and define the variable.  */
1477      current_variable_set_list = vlist;
1478      v = try_variable_definition (flocp, defn, origin, 1);
1479      if (!v)
1480        error (flocp, _("Malformed per-target variable definition"));
1481      v->per_target = 1;
1482
1483      /* If it's not an override, check to see if there was a command-line
1484         setting.  If so, reset the value.  */
1485      if (origin != o_override)
1486        {
1487          struct variable *gv;
1488          int len = strlen(v->name);
1489
1490          current_variable_set_list = global;
1491          gv = lookup_variable (v->name, len);
1492          if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1493            define_variable_in_set (v->name, len, gv->value, gv->origin,
1494                                    gv->recursive, vlist->set, flocp);
1495        }
1496
1497      /* Free name if not needed further.  */
1498      if (name != fname && (name < fname || name > fname + strlen (fname)))
1499        free (name);
1500    }
1501
1502  current_variable_set_list = global;
1503}
1504
1505/* Record a description line for files FILENAMES,
1506   with dependencies DEPS, commands to execute described
1507   by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1508   TWO_COLON is nonzero if a double colon was used.
1509   If not nil, PATTERN is the `%' pattern to make this
1510   a static pattern rule, and PATTERN_PERCENT is a pointer
1511   to the `%' within it.
1512
1513   The links of FILENAMES are freed, and so are any names in it
1514   that are not incorporated into other data structures.  */
1515
1516static void
1517record_files (filenames, pattern, pattern_percent, deps, cmds_started,
1518              commands, commands_idx, two_colon, flocp, set_default)
1519     struct nameseq *filenames;
1520     char *pattern, *pattern_percent;
1521     struct dep *deps;
1522     unsigned int cmds_started;
1523     char *commands;
1524     unsigned int commands_idx;
1525     int two_colon;
1526     const struct floc *flocp;
1527     int set_default;
1528{
1529  struct nameseq *nextf;
1530  int implicit = 0;
1531  unsigned int max_targets = 0, target_idx = 0;
1532  char **targets = 0, **target_percents = 0;
1533  struct commands *cmds;
1534
1535  if (commands_idx > 0)
1536    {
1537      cmds = (struct commands *) xmalloc (sizeof (struct commands));
1538      cmds->fileinfo.filenm = flocp->filenm;
1539      cmds->fileinfo.lineno = cmds_started;
1540      cmds->commands = savestring (commands, commands_idx);
1541      cmds->command_lines = 0;
1542    }
1543  else
1544    cmds = 0;
1545
1546  for (; filenames != 0; filenames = nextf)
1547    {
1548
1549      register char *name = filenames->name;
1550      register struct file *f;
1551      register struct dep *d;
1552      struct dep *this;
1553      char *implicit_percent;
1554
1555      nextf = filenames->next;
1556      free (filenames);
1557
1558      implicit_percent = find_percent (name);
1559      implicit |= implicit_percent != 0;
1560
1561      if (implicit && pattern != 0)
1562        fatal (flocp, _("mixed implicit and static pattern rules"));
1563
1564      if (implicit && implicit_percent == 0)
1565        fatal (flocp, _("mixed implicit and normal rules"));
1566
1567      if (implicit)
1568        {
1569          if (targets == 0)
1570            {
1571              max_targets = 5;
1572              targets = (char **) xmalloc (5 * sizeof (char *));
1573              target_percents = (char **) xmalloc (5 * sizeof (char *));
1574              target_idx = 0;
1575            }
1576          else if (target_idx == max_targets - 1)
1577            {
1578              max_targets += 5;
1579              targets = (char **) xrealloc ((char *) targets,
1580                                            max_targets * sizeof (char *));
1581              target_percents
1582                = (char **) xrealloc ((char *) target_percents,
1583                                      max_targets * sizeof (char *));
1584            }
1585          targets[target_idx] = name;
1586          target_percents[target_idx] = implicit_percent;
1587          ++target_idx;
1588          continue;
1589        }
1590
1591      /* If there are multiple filenames, copy the chain DEPS
1592         for all but the last one.  It is not safe for the same deps
1593         to go in more than one place in the data base.  */
1594      this = nextf != 0 ? copy_dep_chain (deps) : deps;
1595
1596      if (pattern != 0)
1597        {
1598          /* If this is an extended static rule:
1599             `targets: target%pattern: dep%pattern; cmds',
1600             translate each dependency pattern into a plain filename
1601             using the target pattern and this target's name.  */
1602          if (!pattern_matches (pattern, pattern_percent, name))
1603            {
1604              /* Give a warning if the rule is meaningless.  */
1605              error (flocp,
1606                     _("target `%s' doesn't match the target pattern"), name);
1607              this = 0;
1608            }
1609          else
1610            {
1611              /* We use patsubst_expand to do the work of translating
1612                 the target pattern, the target's name and the dependencies'
1613                 patterns into plain dependency names.  */
1614              char *buffer = variable_expand ("");
1615
1616              for (d = this; d != 0; d = d->next)
1617                {
1618                  char *o;
1619                  char *percent = find_percent (d->name);
1620                  if (percent == 0)
1621                    continue;
1622                  o = patsubst_expand (buffer, name, pattern, d->name,
1623                                       pattern_percent, percent);
1624                  /* If the name expanded to the empty string, that's
1625                     illegal.  */
1626                  if (o == buffer)
1627                    fatal (flocp,
1628                           _("target `%s' leaves prerequisite pattern empty"),
1629                           name);
1630                  free (d->name);
1631                  d->name = savestring (buffer, o - buffer);
1632                }
1633            }
1634        }
1635
1636      if (!two_colon)
1637        {
1638          /* Single-colon.  Combine these dependencies
1639             with others in file's existing record, if any.  */
1640          f = enter_file (name);
1641
1642          if (f->double_colon)
1643            fatal (flocp,
1644                   _("target file `%s' has both : and :: entries"), f->name);
1645
1646          /* If CMDS == F->CMDS, this target was listed in this rule
1647             more than once.  Just give a warning since this is harmless.  */
1648          if (cmds != 0 && cmds == f->cmds)
1649            error (flocp,
1650                   _("target `%s' given more than once in the same rule."),
1651                   f->name);
1652
1653          /* Check for two single-colon entries both with commands.
1654             Check is_target so that we don't lose on files such as .c.o
1655             whose commands were preinitialized.  */
1656          else if (cmds != 0 && f->cmds != 0 && f->is_target)
1657            {
1658              error (&cmds->fileinfo,
1659                     _("warning: overriding commands for target `%s'"),
1660                     f->name);
1661              error (&f->cmds->fileinfo,
1662                     _("warning: ignoring old commands for target `%s'"),
1663                     f->name);
1664            }
1665
1666          f->is_target = 1;
1667
1668          /* Defining .DEFAULT with no deps or cmds clears it.  */
1669          if (f == default_file && this == 0 && cmds == 0)
1670            f->cmds = 0;
1671          if (cmds != 0)
1672            f->cmds = cmds;
1673          /* Defining .SUFFIXES with no dependencies
1674             clears out the list of suffixes.  */
1675          if (f == suffix_file && this == 0)
1676            {
1677              d = f->deps;
1678              while (d != 0)
1679                {
1680                  struct dep *nextd = d->next;
1681                  free (d->name);
1682                  free ((char *)d);
1683                  d = nextd;
1684                }
1685              f->deps = 0;
1686            }
1687          else if (f->deps != 0)
1688            {
1689              /* Add the file's old deps and the new ones in THIS together.  */
1690
1691              struct dep *firstdeps, *moredeps;
1692              if (cmds != 0)
1693                {
1694                  /* This is the rule with commands, so put its deps first.
1695                     The rationale behind this is that $< expands to the
1696                     first dep in the chain, and commands use $< expecting
1697                     to get the dep that rule specifies.  */
1698                  firstdeps = this;
1699                  moredeps = f->deps;
1700                }
1701              else
1702                {
1703                  /* Append the new deps to the old ones.  */
1704                  firstdeps = f->deps;
1705                  moredeps = this;
1706                }
1707
1708              if (firstdeps == 0)
1709                firstdeps = moredeps;
1710              else
1711                {
1712                  d = firstdeps;
1713                  while (d->next != 0)
1714                    d = d->next;
1715                  d->next = moredeps;
1716                }
1717
1718              f->deps = firstdeps;
1719            }
1720          else
1721            f->deps = this;
1722
1723          /* If this is a static pattern rule, set the file's stem to
1724             the part of its name that matched the `%' in the pattern,
1725             so you can use $* in the commands.  */
1726          if (pattern != 0)
1727            {
1728              static char *percent = "%";
1729              char *buffer = variable_expand ("");
1730              char *o = patsubst_expand (buffer, name, pattern, percent,
1731                                         pattern_percent, percent);
1732              f->stem = savestring (buffer, o - buffer);
1733            }
1734        }
1735      else
1736        {
1737          /* Double-colon.  Make a new record
1738             even if the file already has one.  */
1739          f = lookup_file (name);
1740          /* Check for both : and :: rules.  Check is_target so
1741             we don't lose on default suffix rules or makefiles.  */
1742          if (f != 0 && f->is_target && !f->double_colon)
1743            fatal (flocp,
1744                   _("target file `%s' has both : and :: entries"), f->name);
1745          f = enter_file (name);
1746          /* If there was an existing entry and it was a double-colon
1747             entry, enter_file will have returned a new one, making it the
1748             prev pointer of the old one, and setting its double_colon
1749             pointer to the first one.  */
1750          if (f->double_colon == 0)
1751            /* This is the first entry for this name, so we must
1752               set its double_colon pointer to itself.  */
1753            f->double_colon = f;
1754          f->is_target = 1;
1755          f->deps = this;
1756          f->cmds = cmds;
1757        }
1758
1759      /* Free name if not needed further.  */
1760      if (f != 0 && name != f->name
1761          && (name < f->name || name > f->name + strlen (f->name)))
1762        {
1763          free (name);
1764          name = f->name;
1765        }
1766
1767      /* See if this is first target seen whose name does
1768         not start with a `.', unless it contains a slash.  */
1769      if (default_goal_file == 0 && set_default
1770          && (*name != '.' || strchr (name, '/') != 0
1771#if defined(__MSDOS__) || defined(WINDOWS32)
1772                           || strchr (name, '\\') != 0
1773#endif
1774              ))
1775        {
1776          int reject = 0;
1777
1778          /* If this file is a suffix, don't
1779             let it be the default goal file.  */
1780
1781          for (d = suffix_file->deps; d != 0; d = d->next)
1782            {
1783              register struct dep *d2;
1784              if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1785                {
1786                  reject = 1;
1787                  break;
1788                }
1789              for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1790                {
1791                  register unsigned int len = strlen (dep_name (d2));
1792                  if (!strneq (name, dep_name (d2), len))
1793                    continue;
1794                  if (streq (name + len, dep_name (d)))
1795                    {
1796                      reject = 1;
1797                      break;
1798                    }
1799                }
1800              if (reject)
1801                break;
1802            }
1803
1804          if (!reject)
1805            default_goal_file = f;
1806        }
1807    }
1808
1809  if (implicit)
1810    {
1811      targets[target_idx] = 0;
1812      target_percents[target_idx] = 0;
1813      create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
1814      free ((char *) target_percents);
1815    }
1816}
1817
1818/* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
1819   Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
1820   Quoting backslashes are removed from STRING by compacting it into
1821   itself.  Returns a pointer to the first unquoted STOPCHAR if there is
1822   one, or nil if there are none.  */
1823
1824char *
1825find_char_unquote (string, stopchars, blank)
1826     char *string;
1827     char *stopchars;
1828     int blank;
1829{
1830  unsigned int string_len = 0;
1831  register char *p = string;
1832
1833  while (1)
1834    {
1835      while (*p != '\0' && strchr (stopchars, *p) == 0
1836             && (!blank || !isblank ((unsigned char)*p)))
1837        ++p;
1838      if (*p == '\0')
1839        break;
1840
1841      if (p > string && p[-1] == '\\')
1842        {
1843          /* Search for more backslashes.  */
1844          register int i = -2;
1845          while (&p[i] >= string && p[i] == '\\')
1846            --i;
1847          ++i;
1848          /* Only compute the length if really needed.  */
1849          if (string_len == 0)
1850            string_len = strlen (string);
1851          /* The number of backslashes is now -I.
1852             Copy P over itself to swallow half of them.  */
1853          bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
1854          p += i / 2;
1855          if (i % 2 == 0)
1856            /* All the backslashes quoted each other; the STOPCHAR was
1857               unquoted.  */
1858            return p;
1859
1860          /* The STOPCHAR was quoted by a backslash.  Look for another.  */
1861        }
1862      else
1863        /* No backslash in sight.  */
1864        return p;
1865    }
1866
1867  /* Never hit a STOPCHAR or blank (with BLANK nonzero).  */
1868  return 0;
1869}
1870
1871/* Search PATTERN for an unquoted %.  */
1872
1873char *
1874find_percent (pattern)
1875     char *pattern;
1876{
1877  return find_char_unquote (pattern, "%", 0);
1878}
1879
1880/* Parse a string into a sequence of filenames represented as a
1881   chain of struct nameseq's in reverse order and return that chain.
1882
1883   The string is passed as STRINGP, the address of a string pointer.
1884   The string pointer is updated to point at the first character
1885   not parsed, which either is a null char or equals STOPCHAR.
1886
1887   SIZE is how big to construct chain elements.
1888   This is useful if we want them actually to be other structures
1889   that have room for additional info.
1890
1891   If STRIP is nonzero, strip `./'s off the beginning.  */
1892
1893struct nameseq *
1894parse_file_seq (stringp, stopchar, size, strip)
1895     char **stringp;
1896     int stopchar;
1897     unsigned int size;
1898     int strip;
1899{
1900  register struct nameseq *new = 0;
1901  register struct nameseq *new1, *lastnew1;
1902  register char *p = *stringp;
1903  char *q;
1904  char *name;
1905  char stopchars[3];
1906
1907#ifdef VMS
1908  stopchars[0] = ',';
1909  stopchars[1] = stopchar;
1910  stopchars[2] = '\0';
1911#else
1912  stopchars[0] = stopchar;
1913  stopchars[1] = '\0';
1914#endif
1915
1916  while (1)
1917    {
1918      /* Skip whitespace; see if any more names are left.  */
1919      p = next_token (p);
1920      if (*p == '\0')
1921        break;
1922      if (*p == stopchar)
1923        break;
1924
1925      /* Yes, find end of next name.  */
1926      q = p;
1927      p = find_char_unquote (q, stopchars, 1);
1928#ifdef VMS
1929        /* convert comma separated list to space separated */
1930      if (p && *p == ',')
1931        *p =' ';
1932#endif
1933#ifdef _AMIGA
1934      if (stopchar == ':' && p && *p == ':'
1935          && !(isspace ((unsigned char)p[1]) || !p[1]
1936               || isspace ((unsigned char)p[-1])))
1937      {
1938        p = find_char_unquote (p+1, stopchars, 1);
1939      }
1940#endif
1941#if defined(WINDOWS32) || defined(__MSDOS__)
1942    /* For WINDOWS32, skip a "C:\..." or a "C:/..." until we find the
1943       first colon which isn't followed by a slash or a backslash.
1944       Note that tokens separated by spaces should be treated as separate
1945       tokens since make doesn't allow path names with spaces */
1946    if (stopchar == ':')
1947      while (p != 0 && !isspace ((unsigned char)*p) &&
1948             (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
1949        p = find_char_unquote (p + 1, stopchars, 1);
1950#endif
1951      if (p == 0)
1952        p = q + strlen (q);
1953
1954      if (strip)
1955#ifdef VMS
1956        /* Skip leading `[]'s.  */
1957        while (p - q > 2 && q[0] == '[' && q[1] == ']')
1958#else
1959        /* Skip leading `./'s.  */
1960        while (p - q > 2 && q[0] == '.' && q[1] == '/')
1961#endif
1962          {
1963            q += 2;             /* Skip "./".  */
1964            while (q < p && *q == '/')
1965              /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
1966              ++q;
1967          }
1968
1969      /* Extract the filename just found, and skip it.  */
1970
1971      if (q == p)
1972        /* ".///" was stripped to "". */
1973#ifdef VMS
1974        continue;
1975#else
1976#ifdef _AMIGA
1977        name = savestring ("", 0);
1978#else
1979        name = savestring ("./", 2);
1980#endif
1981#endif
1982      else
1983#ifdef VMS
1984/* VMS filenames can have a ':' in them but they have to be '\'ed but we need
1985 *  to remove this '\' before we can use the filename.
1986 * Savestring called because q may be read-only string constant.
1987 */
1988        {
1989          char *qbase = xstrdup (q);
1990          char *pbase = qbase + (p-q);
1991          char *q1 = qbase;
1992          char *q2 = q1;
1993          char *p1 = pbase;
1994
1995          while (q1 != pbase)
1996            {
1997              if (*q1 == '\\' && *(q1+1) == ':')
1998                {
1999                  q1++;
2000                  p1--;
2001                }
2002              *q2++ = *q1++;
2003            }
2004          name = savestring (qbase, p1 - qbase);
2005          free (qbase);
2006        }
2007#else
2008        name = savestring (q, p - q);
2009#endif
2010
2011      /* Add it to the front of the chain.  */
2012      new1 = (struct nameseq *) xmalloc (size);
2013      new1->name = name;
2014      new1->next = new;
2015      new = new1;
2016    }
2017
2018#ifndef NO_ARCHIVES
2019
2020  /* Look for multi-word archive references.
2021     They are indicated by a elt ending with an unmatched `)' and
2022     an elt further down the chain (i.e., previous in the file list)
2023     with an unmatched `(' (e.g., "lib(mem").  */
2024
2025  new1 = new;
2026  lastnew1 = 0;
2027  while (new1 != 0)
2028    if (new1->name[0] != '('    /* Don't catch "(%)" and suchlike.  */
2029        && new1->name[strlen (new1->name) - 1] == ')'
2030        && strchr (new1->name, '(') == 0)
2031      {
2032        /* NEW1 ends with a `)' but does not contain a `('.
2033           Look back for an elt with an opening `(' but no closing `)'.  */
2034
2035        struct nameseq *n = new1->next, *lastn = new1;
2036        char *paren = 0;
2037        while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2038          {
2039            lastn = n;
2040            n = n->next;
2041          }
2042        if (n != 0
2043            /* Ignore something starting with `(', as that cannot actually
2044               be an archive-member reference (and treating it as such
2045               results in an empty file name, which causes much lossage).  */
2046            && n->name[0] != '(')
2047          {
2048            /* N is the first element in the archive group.
2049               Its name looks like "lib(mem" (with no closing `)').  */
2050
2051            char *libname;
2052
2053            /* Copy "lib(" into LIBNAME.  */
2054            ++paren;
2055            libname = (char *) alloca (paren - n->name + 1);
2056            bcopy (n->name, libname, paren - n->name);
2057            libname[paren - n->name] = '\0';
2058
2059            if (*paren == '\0')
2060              {
2061                /* N was just "lib(", part of something like "lib( a b)".
2062                   Edit it out of the chain and free its storage.  */
2063                lastn->next = n->next;
2064                free (n->name);
2065                free ((char *) n);
2066                /* LASTN->next is the new stopping elt for the loop below.  */
2067                n = lastn->next;
2068              }
2069            else
2070              {
2071                /* Replace N's name with the full archive reference.  */
2072                name = concat (libname, paren, ")");
2073                free (n->name);
2074                n->name = name;
2075              }
2076
2077            if (new1->name[1] == '\0')
2078              {
2079                /* NEW1 is just ")", part of something like "lib(a b )".
2080                   Omit it from the chain and free its storage.  */
2081                if (lastnew1 == 0)
2082                  new = new1->next;
2083                else
2084                  lastnew1->next = new1->next;
2085                lastn = new1;
2086                new1 = new1->next;
2087                free (lastn->name);
2088                free ((char *) lastn);
2089              }
2090            else
2091              {
2092                /* Replace also NEW1->name, which already has closing `)'.  */
2093                name = concat (libname, new1->name, "");
2094                free (new1->name);
2095                new1->name = name;
2096                new1 = new1->next;
2097              }
2098
2099            /* Trace back from NEW1 (the end of the list) until N
2100               (the beginning of the list), rewriting each name
2101               with the full archive reference.  */
2102
2103            while (new1 != n)
2104              {
2105                name = concat (libname, new1->name, ")");
2106                free (new1->name);
2107                new1->name = name;
2108                lastnew1 = new1;
2109                new1 = new1->next;
2110              }
2111          }
2112        else
2113          {
2114            /* No frobnication happening.  Just step down the list.  */
2115            lastnew1 = new1;
2116            new1 = new1->next;
2117          }
2118      }
2119    else
2120      {
2121        lastnew1 = new1;
2122        new1 = new1->next;
2123      }
2124
2125#endif
2126
2127  *stringp = p;
2128  return new;
2129}
2130
2131/* Read a line of text from STREAM into LINEBUFFER.
2132   Combine continuation lines into one line.
2133   Return the number of actual lines read (> 1 if hacked continuation lines).
2134 */
2135
2136static unsigned long
2137readline (linebuffer, stream, flocp)
2138     struct linebuffer *linebuffer;
2139     FILE *stream;
2140     const struct floc *flocp;
2141{
2142  char *buffer = linebuffer->buffer;
2143  register char *p = linebuffer->buffer;
2144  register char *end = p + linebuffer->size;
2145  register int len, lastlen = 0;
2146  register char *p2;
2147  register unsigned int nlines = 0;
2148  register int backslash;
2149
2150  *p = '\0';
2151
2152  while (fgets (p, end - p, stream) != 0)
2153    {
2154      len = strlen (p);
2155      if (len == 0)
2156        {
2157          /* This only happens when the first thing on the line is a '\0'.
2158             It is a pretty hopeless case, but (wonder of wonders) Athena
2159             lossage strikes again!  (xmkmf puts NULs in its makefiles.)
2160             There is nothing really to be done; we synthesize a newline so
2161             the following line doesn't appear to be part of this line.  */
2162          error (flocp, _("warning: NUL character seen; rest of line ignored"));
2163          p[0] = '\n';
2164          len = 1;
2165        }
2166
2167      p += len;
2168      if (p[-1] != '\n')
2169        {
2170          /* Probably ran out of buffer space.  */
2171          register unsigned int p_off = p - buffer;
2172          linebuffer->size *= 2;
2173          buffer = (char *) xrealloc (buffer, linebuffer->size);
2174          p = buffer + p_off;
2175          end = buffer + linebuffer->size;
2176          linebuffer->buffer = buffer;
2177          *p = '\0';
2178          lastlen = len;
2179          continue;
2180        }
2181
2182      ++nlines;
2183
2184#if !defined(WINDOWS32) && !defined(__MSDOS__)
2185      /* Check to see if the line was really ended with CRLF; if so ignore
2186         the CR.  */
2187      if (len > 1 && p[-2] == '\r')
2188        {
2189          --len;
2190          --p;
2191          p[-1] = '\n';
2192        }
2193#endif
2194
2195      if (len == 1 && p > buffer)
2196        /* P is pointing at a newline and it's the beginning of
2197           the buffer returned by the last fgets call.  However,
2198           it is not necessarily the beginning of a line if P is
2199           pointing past the beginning of the holding buffer.
2200           If the buffer was just enlarged (right before the newline),
2201           we must account for that, so we pretend that the two lines
2202           were one line.  */
2203        len += lastlen;
2204      lastlen = len;
2205      backslash = 0;
2206      for (p2 = p - 2; --len > 0; --p2)
2207        {
2208          if (*p2 == '\\')
2209            backslash = !backslash;
2210          else
2211            break;
2212        }
2213
2214      if (!backslash)
2215        {
2216          p[-1] = '\0';
2217          break;
2218        }
2219
2220      if (end - p <= 1)
2221        {
2222          /* Enlarge the buffer.  */
2223          register unsigned int p_off = p - buffer;
2224          linebuffer->size *= 2;
2225          buffer = (char *) xrealloc (buffer, linebuffer->size);
2226          p = buffer + p_off;
2227          end = buffer + linebuffer->size;
2228          linebuffer->buffer = buffer;
2229        }
2230    }
2231
2232  if (ferror (stream))
2233    pfatal_with_name (flocp->filenm);
2234
2235  return nlines;
2236}
2237
2238/* Parse the next "makefile word" from the input buffer, and return info
2239   about it.
2240
2241   A "makefile word" is one of:
2242
2243     w_bogus        Should never happen
2244     w_eol          End of input
2245     w_static       A static word; cannot be expanded
2246     w_variable     A word containing one or more variables/functions
2247     w_colon        A colon
2248     w_dcolon       A double-colon
2249     w_semicolon    A semicolon
2250     w_comment      A comment character
2251     w_varassign    A variable assignment operator (=, :=, +=, or ?=)
2252
2253   Note that this function is only used when reading certain parts of the
2254   makefile.  Don't use it where special rules hold sway (RHS of a variable,
2255   in a command list, etc.)  */
2256
2257static enum make_word_type
2258get_next_mword (buffer, delim, startp, length)
2259     char *buffer;
2260     char *delim;
2261     char **startp;
2262     unsigned int *length;
2263{
2264  enum make_word_type wtype = w_bogus;
2265  char *p = buffer, *beg;
2266  char c;
2267
2268  /* Skip any leading whitespace.  */
2269  while (isblank ((unsigned char)*p))
2270    ++p;
2271
2272  beg = p;
2273  c = *(p++);
2274  switch (c)
2275    {
2276    case '\0':
2277      wtype = w_eol;
2278      break;
2279
2280    case '#':
2281      wtype = w_comment;
2282      break;
2283
2284    case ';':
2285      wtype = w_semicolon;
2286      break;
2287
2288    case '=':
2289      wtype = w_varassign;
2290      break;
2291
2292    case ':':
2293      wtype = w_colon;
2294      switch (*p)
2295        {
2296        case ':':
2297          ++p;
2298          wtype = w_dcolon;
2299          break;
2300
2301        case '=':
2302          ++p;
2303          wtype = w_varassign;
2304          break;
2305        }
2306      break;
2307
2308    case '+':
2309    case '?':
2310      if (*p == '=')
2311        {
2312          ++p;
2313          wtype = w_varassign;
2314          break;
2315        }
2316
2317    default:
2318      if (delim && strchr (delim, c))
2319        wtype = w_static;
2320      break;
2321    }
2322
2323  /* Did we find something?  If so, return now.  */
2324  if (wtype != w_bogus)
2325    goto done;
2326
2327  /* This is some non-operator word.  A word consists of the longest
2328     string of characters that doesn't contain whitespace, one of [:=#],
2329     or [?+]=, or one of the chars in the DELIM string.  */
2330
2331  /* We start out assuming a static word; if we see a variable we'll
2332     adjust our assumptions then.  */
2333  wtype = w_static;
2334
2335  /* We already found the first value of "c", above.  */
2336  while (1)
2337    {
2338      char closeparen;
2339      int count;
2340
2341      switch (c)
2342        {
2343        case '\0':
2344        case ' ':
2345        case '\t':
2346        case '=':
2347        case '#':
2348          goto done_word;
2349
2350        case ':':
2351#if defined(__MSDOS__) || defined(WINDOWS32)
2352          /* A word CAN include a colon in its drive spec.  The drive
2353             spec is allowed either at the beginning of a word, or as part
2354             of the archive member name, like in "libfoo.a(d:/foo/bar.o)".  */
2355          if (!(p - beg >= 2
2356                && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2357                && (p - beg == 2 || p[-3] == '(')))
2358#endif
2359          goto done_word;
2360
2361        case '$':
2362          c = *(p++);
2363          if (c == '$')
2364            break;
2365
2366          /* This is a variable reference, so note that it's expandable.
2367             Then read it to the matching close paren.  */
2368          wtype = w_variable;
2369
2370          if (c == '(')
2371            closeparen = ')';
2372          else if (c == '{')
2373            closeparen = '}';
2374          else
2375            /* This is a single-letter variable reference.  */
2376            break;
2377
2378          for (count=0; *p != '\0'; ++p)
2379            {
2380              if (*p == c)
2381                ++count;
2382              else if (*p == closeparen && --count < 0)
2383                {
2384                  ++p;
2385                  break;
2386                }
2387            }
2388          break;
2389
2390        case '?':
2391        case '+':
2392          if (*p == '=')
2393            goto done_word;
2394          break;
2395
2396        case '\\':
2397          switch (*p)
2398            {
2399            case ':':
2400            case ';':
2401            case '=':
2402            case '\\':
2403              ++p;
2404              break;
2405            }
2406          break;
2407
2408        default:
2409          if (delim && strchr (delim, c))
2410            goto done_word;
2411          break;
2412        }
2413
2414      c = *(p++);
2415    }
2416 done_word:
2417  --p;
2418
2419 done:
2420  if (startp)
2421    *startp = beg;
2422  if (length)
2423    *length = p - beg;
2424  return wtype;
2425}
2426
2427/* Construct the list of include directories
2428   from the arguments and the default list.  */
2429
2430void
2431construct_include_path (arg_dirs)
2432     char **arg_dirs;
2433{
2434  register unsigned int i;
2435#ifdef VAXC             /* just don't ask ... */
2436  stat_t stbuf;
2437#else
2438  struct stat stbuf;
2439#endif
2440  /* Table to hold the dirs.  */
2441
2442  register unsigned int defsize = (sizeof (default_include_directories)
2443                                   / sizeof (default_include_directories[0]));
2444  register unsigned int max = 5;
2445  register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2446  register unsigned int idx = 0;
2447
2448#ifdef  __MSDOS__
2449  defsize++;
2450#endif
2451
2452  /* First consider any dirs specified with -I switches.
2453     Ignore dirs that don't exist.  */
2454
2455  if (arg_dirs != 0)
2456    while (*arg_dirs != 0)
2457      {
2458        char *dir = *arg_dirs++;
2459
2460        if (dir[0] == '~')
2461          {
2462            char *expanded = tilde_expand (dir);
2463            if (expanded != 0)
2464              dir = expanded;
2465          }
2466
2467        if (stat (dir, &stbuf) == 0 && S_ISDIR (stbuf.st_mode))
2468          {
2469            if (idx == max - 1)
2470              {
2471                max += 5;
2472                dirs = (char **)
2473                  xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2474              }
2475            dirs[idx++] = dir;
2476          }
2477        else if (dir != arg_dirs[-1])
2478          free (dir);
2479      }
2480
2481  /* Now add at the end the standard default dirs.  */
2482
2483#ifdef  __MSDOS__
2484  {
2485    /* The environment variable $DJDIR holds the root of the
2486       DJGPP directory tree; add ${DJDIR}/include.  */
2487    struct variable *djdir = lookup_variable ("DJDIR", 5);
2488
2489    if (djdir)
2490      {
2491        char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2492
2493        strcat (strcpy (defdir, djdir->value), "/include");
2494        dirs[idx++] = defdir;
2495      }
2496  }
2497#endif
2498
2499  for (i = 0; default_include_directories[i] != 0; ++i)
2500    if (stat (default_include_directories[i], &stbuf) == 0
2501        && S_ISDIR (stbuf.st_mode))
2502      dirs[idx++] = default_include_directories[i];
2503
2504  dirs[idx] = 0;
2505
2506  /* Now compute the maximum length of any name in it.  */
2507
2508  max_incl_len = 0;
2509  for (i = 0; i < idx; ++i)
2510    {
2511      unsigned int len = strlen (dirs[i]);
2512      /* If dir name is written with a trailing slash, discard it.  */
2513      if (dirs[i][len - 1] == '/')
2514        /* We can't just clobber a null in because it may have come from
2515           a literal string and literal strings may not be writable.  */
2516        dirs[i] = savestring (dirs[i], len - 1);
2517      if (len > max_incl_len)
2518        max_incl_len = len;
2519    }
2520
2521  include_directories = dirs;
2522}
2523
2524/* Expand ~ or ~USER at the beginning of NAME.
2525   Return a newly malloc'd string or 0.  */
2526
2527char *
2528tilde_expand (name)
2529     char *name;
2530{
2531#ifndef VMS
2532  if (name[1] == '/' || name[1] == '\0')
2533    {
2534      extern char *getenv ();
2535      char *home_dir;
2536      int is_variable;
2537
2538      {
2539        /* Turn off --warn-undefined-variables while we expand HOME.  */
2540        int save = warn_undefined_variables_flag;
2541        warn_undefined_variables_flag = 0;
2542
2543        home_dir = allocated_variable_expand ("$(HOME)");
2544
2545        warn_undefined_variables_flag = save;
2546      }
2547
2548      is_variable = home_dir[0] != '\0';
2549      if (!is_variable)
2550        {
2551          free (home_dir);
2552          home_dir = getenv ("HOME");
2553        }
2554#if !defined(_AMIGA) && !defined(WINDOWS32)
2555      if (home_dir == 0 || home_dir[0] == '\0')
2556        {
2557          extern char *getlogin ();
2558          char *logname = getlogin ();
2559          home_dir = 0;
2560          if (logname != 0)
2561            {
2562              struct passwd *p = getpwnam (logname);
2563              if (p != 0)
2564                home_dir = p->pw_dir;
2565            }
2566        }
2567#endif /* !AMIGA && !WINDOWS32 */
2568      if (home_dir != 0)
2569        {
2570          char *new = concat (home_dir, "", name + 1);
2571          if (is_variable)
2572            free (home_dir);
2573          return new;
2574        }
2575    }
2576#if !defined(_AMIGA) && !defined(WINDOWS32)
2577  else
2578    {
2579      struct passwd *pwent;
2580      char *userend = strchr (name + 1, '/');
2581      if (userend != 0)
2582        *userend = '\0';
2583      pwent = getpwnam (name + 1);
2584      if (pwent != 0)
2585        {
2586          if (userend == 0)
2587            return xstrdup (pwent->pw_dir);
2588          else
2589            return concat (pwent->pw_dir, "/", userend + 1);
2590        }
2591      else if (userend != 0)
2592        *userend = '/';
2593    }
2594#endif /* !AMIGA && !WINDOWS32 */
2595#endif /* !VMS */
2596  return 0;
2597}
2598
2599/* Given a chain of struct nameseq's describing a sequence of filenames,
2600   in reverse of the intended order, return a new chain describing the
2601   result of globbing the filenames.  The new chain is in forward order.
2602   The links of the old chain are freed or used in the new chain.
2603   Likewise for the names in the old chain.
2604
2605   SIZE is how big to construct chain elements.
2606   This is useful if we want them actually to be other structures
2607   that have room for additional info.  */
2608
2609struct nameseq *
2610multi_glob (chain, size)
2611     struct nameseq *chain;
2612     unsigned int size;
2613{
2614  extern void dir_setup_glob ();
2615  register struct nameseq *new = 0;
2616  register struct nameseq *old;
2617  struct nameseq *nexto;
2618  glob_t gl;
2619
2620  dir_setup_glob (&gl);
2621
2622  for (old = chain; old != 0; old = nexto)
2623    {
2624#ifndef NO_ARCHIVES
2625      char *memname;
2626#endif
2627
2628      nexto = old->next;
2629
2630      if (old->name[0] == '~')
2631        {
2632          char *newname = tilde_expand (old->name);
2633          if (newname != 0)
2634            {
2635              free (old->name);
2636              old->name = newname;
2637            }
2638        }
2639
2640#ifndef NO_ARCHIVES
2641      if (ar_name (old->name))
2642        {
2643          /* OLD->name is an archive member reference.
2644             Replace it with the archive file name,
2645             and save the member name in MEMNAME.
2646             We will glob on the archive name and then
2647             reattach MEMNAME later.  */
2648          char *arname;
2649          ar_parse_name (old->name, &arname, &memname);
2650          free (old->name);
2651          old->name = arname;
2652        }
2653      else
2654        memname = 0;
2655#endif /* !NO_ARCHIVES */
2656
2657      switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
2658        {
2659        case 0:                 /* Success.  */
2660          {
2661            register int i = gl.gl_pathc;
2662            while (i-- > 0)
2663              {
2664#ifndef NO_ARCHIVES
2665                if (memname != 0)
2666                  {
2667                    /* Try to glob on MEMNAME within the archive.  */
2668                    struct nameseq *found
2669                      = ar_glob (gl.gl_pathv[i], memname, size);
2670                    if (found == 0)
2671                      {
2672                        /* No matches.  Use MEMNAME as-is.  */
2673                        struct nameseq *elt
2674                          = (struct nameseq *) xmalloc (size);
2675                        unsigned int alen = strlen (gl.gl_pathv[i]);
2676                        unsigned int mlen = strlen (memname);
2677                        elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
2678                        bcopy (gl.gl_pathv[i], elt->name, alen);
2679                        elt->name[alen] = '(';
2680                        bcopy (memname, &elt->name[alen + 1], mlen);
2681                        elt->name[alen + 1 + mlen] = ')';
2682                        elt->name[alen + 1 + mlen + 1] = '\0';
2683                        elt->next = new;
2684                        new = elt;
2685                      }
2686                    else
2687                      {
2688                        /* Find the end of the FOUND chain.  */
2689                        struct nameseq *f = found;
2690                        while (f->next != 0)
2691                          f = f->next;
2692
2693                        /* Attach the chain being built to the end of the FOUND
2694                           chain, and make FOUND the new NEW chain.  */
2695                        f->next = new;
2696                        new = found;
2697                      }
2698
2699                    free (memname);
2700                  }
2701                else
2702#endif /* !NO_ARCHIVES */
2703                  {
2704                    struct nameseq *elt = (struct nameseq *) xmalloc (size);
2705                    elt->name = xstrdup (gl.gl_pathv[i]);
2706                    elt->next = new;
2707                    new = elt;
2708                  }
2709              }
2710            globfree (&gl);
2711            free (old->name);
2712            free ((char *)old);
2713            break;
2714          }
2715
2716        case GLOB_NOSPACE:
2717          fatal (NILF, _("virtual memory exhausted"));
2718          break;
2719
2720        default:
2721          old->next = new;
2722          new = old;
2723          break;
2724        }
2725    }
2726
2727  return new;
2728}
Note: See TracBrowser for help on using the repository browser.