OpenCores
URL https://opencores.org/ocsvn/scarts/scarts/trunk

Subversion Repositories scarts

[/] [scarts/] [trunk/] [toolchain/] [scarts-gcc/] [gcc-4.1.1/] [libcpp/] [macro.c] - Blame information for rev 13

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 13 jlechner
/* Part of CPP library.  (Macro and #define handling.)
2
   Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1998,
3
   1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4
   Written by Per Bothner, 1994.
5
   Based on CCCP program by Paul Rubin, June 1986
6
   Adapted to ANSI C, Richard Stallman, Jan 1987
7
 
8
This program is free software; you can redistribute it and/or modify it
9
under the terms of the GNU General Public License as published by the
10
Free Software Foundation; either version 2, or (at your option) any
11
later version.
12
 
13
This program is distributed in the hope that it will be useful,
14
but WITHOUT ANY WARRANTY; without even the implied warranty of
15
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
GNU General Public License for more details.
17
 
18
You should have received a copy of the GNU General Public License
19
along with this program; if not, write to the Free Software
20
Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
 
22
 In other words, you are welcome to use, share and improve this program.
23
 You are forbidden to forbid anyone else to use, share and improve
24
 what you give them.   Help stamp out software-hoarding!  */
25
 
26
#include "config.h"
27
#include "system.h"
28
#include "cpplib.h"
29
#include "internal.h"
30
 
31
typedef struct macro_arg macro_arg;
32
struct macro_arg
33
{
34
  const cpp_token **first;      /* First token in unexpanded argument.  */
35
  const cpp_token **expanded;   /* Macro-expanded argument.  */
36
  const cpp_token *stringified; /* Stringified argument.  */
37
  unsigned int count;           /* # of tokens in argument.  */
38
  unsigned int expanded_count;  /* # of tokens in expanded argument.  */
39
};
40
 
41
/* Macro expansion.  */
42
 
43
static int enter_macro_context (cpp_reader *, cpp_hashnode *);
44
static int builtin_macro (cpp_reader *, cpp_hashnode *);
45
static void push_token_context (cpp_reader *, cpp_hashnode *,
46
                                const cpp_token *, unsigned int);
47
static void push_ptoken_context (cpp_reader *, cpp_hashnode *, _cpp_buff *,
48
                                 const cpp_token **, unsigned int);
49
static _cpp_buff *collect_args (cpp_reader *, const cpp_hashnode *);
50
static cpp_context *next_context (cpp_reader *);
51
static const cpp_token *padding_token (cpp_reader *, const cpp_token *);
52
static void expand_arg (cpp_reader *, macro_arg *);
53
static const cpp_token *new_string_token (cpp_reader *, uchar *, unsigned int);
54
static const cpp_token *stringify_arg (cpp_reader *, macro_arg *);
55
static void paste_all_tokens (cpp_reader *, const cpp_token *);
56
static bool paste_tokens (cpp_reader *, const cpp_token **, const cpp_token *);
57
static void replace_args (cpp_reader *, cpp_hashnode *, cpp_macro *,
58
                          macro_arg *);
59
static _cpp_buff *funlike_invocation_p (cpp_reader *, cpp_hashnode *);
60
static bool create_iso_definition (cpp_reader *, cpp_macro *);
61
 
62
/* #define directive parsing and handling.  */
63
 
64
static cpp_token *alloc_expansion_token (cpp_reader *, cpp_macro *);
65
static cpp_token *lex_expansion_token (cpp_reader *, cpp_macro *);
66
static bool warn_of_redefinition (cpp_reader *, const cpp_hashnode *,
67
                                  const cpp_macro *);
68
static bool parse_params (cpp_reader *, cpp_macro *);
69
static void check_trad_stringification (cpp_reader *, const cpp_macro *,
70
                                        const cpp_string *);
71
 
72
/* Emits a warning if NODE is a macro defined in the main file that
73
   has not been used.  */
74
int
75
_cpp_warn_if_unused_macro (cpp_reader *pfile, cpp_hashnode *node,
76
                           void *v ATTRIBUTE_UNUSED)
77
{
78
  if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
79
    {
80
      cpp_macro *macro = node->value.macro;
81
 
82
      if (!macro->used
83
          && MAIN_FILE_P (linemap_lookup (pfile->line_table, macro->line)))
84
        cpp_error_with_line (pfile, CPP_DL_WARNING, macro->line, 0,
85
                             "macro \"%s\" is not used", NODE_NAME (node));
86
    }
87
 
88
  return 1;
89
}
90
 
91
/* Allocates and returns a CPP_STRING token, containing TEXT of length
92
   LEN, after null-terminating it.  TEXT must be in permanent storage.  */
93
static const cpp_token *
94
new_string_token (cpp_reader *pfile, unsigned char *text, unsigned int len)
95
{
96
  cpp_token *token = _cpp_temp_token (pfile);
97
 
98
  text[len] = '\0';
99
  token->type = CPP_STRING;
100
  token->val.str.len = len;
101
  token->val.str.text = text;
102
  token->flags = 0;
103
  return token;
104
}
105
 
106
static const char * const monthnames[] =
107
{
108
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
109
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
110
};
111
 
112
/* Helper function for builtin_macro.  Returns the text generated by
113
   a builtin macro. */
114
const uchar *
115
_cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node)
116
{
117
  const struct line_map *map;
118
  const uchar *result = NULL;
119
  unsigned int number = 1;
120
 
121
  switch (node->value.builtin)
122
    {
123
    default:
124
      cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
125
                 NODE_NAME (node));
126
      break;
127
 
128
    case BT_FILE:
129
    case BT_BASE_FILE:
130
      {
131
        unsigned int len;
132
        const char *name;
133
        uchar *buf;
134
        map = linemap_lookup (pfile->line_table, pfile->line_table->highest_line);
135
 
136
        if (node->value.builtin == BT_BASE_FILE)
137
          while (! MAIN_FILE_P (map))
138
            map = INCLUDED_FROM (pfile->line_table, map);
139
 
140
        name = map->to_file;
141
        len = strlen (name);
142
        buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
143
        result = buf;
144
        *buf = '"';
145
        buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
146
        *buf++ = '"';
147
        *buf = '\0';
148
      }
149
      break;
150
 
151
    case BT_INCLUDE_LEVEL:
152
      /* The line map depth counts the primary source as level 1, but
153
         historically __INCLUDE_DEPTH__ has called the primary source
154
         level 0.  */
155
      number = pfile->line_table->depth - 1;
156
      break;
157
 
158
    case BT_SPECLINE:
159
      map = &pfile->line_table->maps[pfile->line_table->used-1];
160
      /* If __LINE__ is embedded in a macro, it must expand to the
161
         line of the macro's invocation, not its definition.
162
         Otherwise things like assert() will not work properly.  */
163
      if (CPP_OPTION (pfile, traditional))
164
        number = pfile->line_table->highest_line;
165
      else
166
        number = pfile->cur_token[-1].src_loc;
167
      number = SOURCE_LINE (map, number);
168
      break;
169
 
170
      /* __STDC__ has the value 1 under normal circumstances.
171
         However, if (a) we are in a system header, (b) the option
172
         stdc_0_in_system_headers is true (set by target config), and
173
         (c) we are not in strictly conforming mode, then it has the
174
         value 0.  (b) and (c) are already checked in cpp_init_builtins.  */
175
    case BT_STDC:
176
      if (cpp_in_system_header (pfile))
177
        number = 0;
178
      else
179
        number = 1;
180
      break;
181
 
182
    case BT_DATE:
183
    case BT_TIME:
184
      if (pfile->date == NULL)
185
        {
186
          /* Allocate __DATE__ and __TIME__ strings from permanent
187
             storage.  We only do this once, and don't generate them
188
             at init time, because time() and localtime() are very
189
             slow on some systems.  */
190
          time_t tt;
191
          struct tm *tb = NULL;
192
 
193
          /* (time_t) -1 is a legitimate value for "number of seconds
194
             since the Epoch", so we have to do a little dance to
195
             distinguish that from a genuine error.  */
196
          errno = 0;
197
          tt = time(NULL);
198
          if (tt != (time_t)-1 || errno == 0)
199
            tb = localtime (&tt);
200
 
201
          if (tb)
202
            {
203
              pfile->date = _cpp_unaligned_alloc (pfile,
204
                                                  sizeof ("\"Oct 11 1347\""));
205
              sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
206
                       monthnames[tb->tm_mon], tb->tm_mday,
207
                       tb->tm_year + 1900);
208
 
209
              pfile->time = _cpp_unaligned_alloc (pfile,
210
                                                  sizeof ("\"12:34:56\""));
211
              sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
212
                       tb->tm_hour, tb->tm_min, tb->tm_sec);
213
            }
214
          else
215
            {
216
              cpp_errno (pfile, CPP_DL_WARNING,
217
                         "could not determine date and time");
218
 
219
              pfile->date = U"\"??? ?? ????\"";
220
              pfile->time = U"\"??:??:??\"";
221
            }
222
        }
223
 
224
      if (node->value.builtin == BT_DATE)
225
        result = pfile->date;
226
      else
227
        result = pfile->time;
228
      break;
229
    }
230
 
231
  if (result == NULL)
232
    {
233
      /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers.  */
234
      result = _cpp_unaligned_alloc (pfile, 21);
235
      sprintf ((char *) result, "%u", number);
236
    }
237
 
238
  return result;
239
}
240
 
241
/* Convert builtin macros like __FILE__ to a token and push it on the
242
   context stack.  Also handles _Pragma, for which a new token may not
243
   be created.  Returns 1 if it generates a new token context, 0 to
244
   return the token to the caller.  */
245
static int
246
builtin_macro (cpp_reader *pfile, cpp_hashnode *node)
247
{
248
  const uchar *buf;
249
  size_t len;
250
  char *nbuf;
251
 
252
  if (node->value.builtin == BT_PRAGMA)
253
    {
254
      /* Don't interpret _Pragma within directives.  The standard is
255
         not clear on this, but to me this makes most sense.  */
256
      if (pfile->state.in_directive)
257
        return 0;
258
 
259
      _cpp_do__Pragma (pfile);
260
      if (pfile->directive_result.type == CPP_PRAGMA)
261
        {
262
          cpp_token *tok = _cpp_temp_token (pfile);
263
          *tok = pfile->directive_result;
264
          push_token_context (pfile, NULL, tok, 1);
265
        }
266
 
267
      return 1;
268
    }
269
 
270
  buf = _cpp_builtin_macro_text (pfile, node);
271
  len = ustrlen (buf);
272
  nbuf = (char *) alloca (len + 1);
273
  memcpy (nbuf, buf, len);
274
  nbuf[len]='\n';
275
 
276
  cpp_push_buffer (pfile, (uchar *) nbuf, len, /* from_stage3 */ true);
277
  _cpp_clean_line (pfile);
278
 
279
  /* Set pfile->cur_token as required by _cpp_lex_direct.  */
280
  pfile->cur_token = _cpp_temp_token (pfile);
281
  push_token_context (pfile, NULL, _cpp_lex_direct (pfile), 1);
282
  if (pfile->buffer->cur != pfile->buffer->rlimit)
283
    cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
284
               NODE_NAME (node));
285
  _cpp_pop_buffer (pfile);
286
 
287
  return 1;
288
}
289
 
290
/* Copies SRC, of length LEN, to DEST, adding backslashes before all
291
   backslashes and double quotes. DEST must be of sufficient size.
292
   Returns a pointer to the end of the string.  */
293
uchar *
294
cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
295
{
296
  while (len--)
297
    {
298
      uchar c = *src++;
299
 
300
      if (c == '\\' || c == '"')
301
        {
302
          *dest++ = '\\';
303
          *dest++ = c;
304
        }
305
      else
306
          *dest++ = c;
307
    }
308
 
309
  return dest;
310
}
311
 
312
/* Convert a token sequence ARG to a single string token according to
313
   the rules of the ISO C #-operator.  */
314
static const cpp_token *
315
stringify_arg (cpp_reader *pfile, macro_arg *arg)
316
{
317
  unsigned char *dest;
318
  unsigned int i, escape_it, backslash_count = 0;
319
  const cpp_token *source = NULL;
320
  size_t len;
321
 
322
  if (BUFF_ROOM (pfile->u_buff) < 3)
323
    _cpp_extend_buff (pfile, &pfile->u_buff, 3);
324
  dest = BUFF_FRONT (pfile->u_buff);
325
  *dest++ = '"';
326
 
327
  /* Loop, reading in the argument's tokens.  */
328
  for (i = 0; i < arg->count; i++)
329
    {
330
      const cpp_token *token = arg->first[i];
331
 
332
      if (token->type == CPP_PADDING)
333
        {
334
          if (source == NULL)
335
            source = token->val.source;
336
          continue;
337
        }
338
 
339
      escape_it = (token->type == CPP_STRING || token->type == CPP_WSTRING
340
                   || token->type == CPP_CHAR || token->type == CPP_WCHAR);
341
 
342
      /* Room for each char being written in octal, initial space and
343
         final quote and NUL.  */
344
      len = cpp_token_len (token);
345
      if (escape_it)
346
        len *= 4;
347
      len += 3;
348
 
349
      if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
350
        {
351
          size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
352
          _cpp_extend_buff (pfile, &pfile->u_buff, len);
353
          dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
354
        }
355
 
356
      /* Leading white space?  */
357
      if (dest - 1 != BUFF_FRONT (pfile->u_buff))
358
        {
359
          if (source == NULL)
360
            source = token;
361
          if (source->flags & PREV_WHITE)
362
            *dest++ = ' ';
363
        }
364
      source = NULL;
365
 
366
      if (escape_it)
367
        {
368
          _cpp_buff *buff = _cpp_get_buff (pfile, len);
369
          unsigned char *buf = BUFF_FRONT (buff);
370
          len = cpp_spell_token (pfile, token, buf, true) - buf;
371
          dest = cpp_quote_string (dest, buf, len);
372
          _cpp_release_buff (pfile, buff);
373
        }
374
      else
375
        dest = cpp_spell_token (pfile, token, dest, true);
376
 
377
      if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
378
        backslash_count++;
379
      else
380
        backslash_count = 0;
381
    }
382
 
383
  /* Ignore the final \ of invalid string literals.  */
384
  if (backslash_count & 1)
385
    {
386
      cpp_error (pfile, CPP_DL_WARNING,
387
                 "invalid string literal, ignoring final '\\'");
388
      dest--;
389
    }
390
 
391
  /* Commit the memory, including NUL, and return the token.  */
392
  *dest++ = '"';
393
  len = dest - BUFF_FRONT (pfile->u_buff);
394
  BUFF_FRONT (pfile->u_buff) = dest + 1;
395
  return new_string_token (pfile, dest - len, len);
396
}
397
 
398
/* Try to paste two tokens.  On success, return nonzero.  In any
399
   case, PLHS is updated to point to the pasted token, which is
400
   guaranteed to not have the PASTE_LEFT flag set.  */
401
static bool
402
paste_tokens (cpp_reader *pfile, const cpp_token **plhs, const cpp_token *rhs)
403
{
404
  unsigned char *buf, *end;
405
  const cpp_token *lhs;
406
  unsigned int len;
407
  bool valid;
408
 
409
  lhs = *plhs;
410
  len = cpp_token_len (lhs) + cpp_token_len (rhs) + 1;
411
  buf = (unsigned char *) alloca (len);
412
  end = cpp_spell_token (pfile, lhs, buf, false);
413
 
414
  /* Avoid comment headers, since they are still processed in stage 3.
415
     It is simpler to insert a space here, rather than modifying the
416
     lexer to ignore comments in some circumstances.  Simply returning
417
     false doesn't work, since we want to clear the PASTE_LEFT flag.  */
418
  if (lhs->type == CPP_DIV && rhs->type != CPP_EQ)
419
    *end++ = ' ';
420
  end = cpp_spell_token (pfile, rhs, end, false);
421
  *end = '\n';
422
 
423
  cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
424
  _cpp_clean_line (pfile);
425
 
426
  /* Set pfile->cur_token as required by _cpp_lex_direct.  */
427
  pfile->cur_token = _cpp_temp_token (pfile);
428
  *plhs = _cpp_lex_direct (pfile);
429
  valid = pfile->buffer->cur == pfile->buffer->rlimit;
430
  _cpp_pop_buffer (pfile);
431
 
432
  return valid;
433
}
434
 
435
/* Handles an arbitrarily long sequence of ## operators, with initial
436
   operand LHS.  This implementation is left-associative,
437
   non-recursive, and finishes a paste before handling succeeding
438
   ones.  If a paste fails, we back up to the RHS of the failing ##
439
   operator before pushing the context containing the result of prior
440
   successful pastes, with the effect that the RHS appears in the
441
   output stream after the pasted LHS normally.  */
442
static void
443
paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
444
{
445
  const cpp_token *rhs;
446
  cpp_context *context = pfile->context;
447
 
448
  do
449
    {
450
      /* Take the token directly from the current context.  We can do
451
         this, because we are in the replacement list of either an
452
         object-like macro, or a function-like macro with arguments
453
         inserted.  In either case, the constraints to #define
454
         guarantee we have at least one more token.  */
455
      if (context->direct_p)
456
        rhs = FIRST (context).token++;
457
      else
458
        rhs = *FIRST (context).ptoken++;
459
 
460
      if (rhs->type == CPP_PADDING)
461
        abort ();
462
 
463
      if (!paste_tokens (pfile, &lhs, rhs))
464
        {
465
          _cpp_backup_tokens (pfile, 1);
466
 
467
          /* Mandatory error for all apart from assembler.  */
468
          if (CPP_OPTION (pfile, lang) != CLK_ASM)
469
            cpp_error (pfile, CPP_DL_ERROR,
470
         "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
471
                       cpp_token_as_text (pfile, lhs),
472
                       cpp_token_as_text (pfile, rhs));
473
          break;
474
        }
475
    }
476
  while (rhs->flags & PASTE_LEFT);
477
 
478
  /* Put the resulting token in its own context.  */
479
  push_token_context (pfile, NULL, lhs, 1);
480
}
481
 
482
/* Returns TRUE if the number of arguments ARGC supplied in an
483
   invocation of the MACRO referenced by NODE is valid.  An empty
484
   invocation to a macro with no parameters should pass ARGC as zero.
485
 
486
   Note that MACRO cannot necessarily be deduced from NODE, in case
487
   NODE was redefined whilst collecting arguments.  */
488
bool
489
_cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
490
{
491
  if (argc == macro->paramc)
492
    return true;
493
 
494
  if (argc < macro->paramc)
495
    {
496
      /* As an extension, a rest argument is allowed to not appear in
497
         the invocation at all.
498
         e.g. #define debug(format, args...) something
499
         debug("string");
500
 
501
         This is exactly the same as if there had been an empty rest
502
         argument - debug("string", ).  */
503
 
504
      if (argc + 1 == macro->paramc && macro->variadic)
505
        {
506
          if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
507
            cpp_error (pfile, CPP_DL_PEDWARN,
508
                       "ISO C99 requires rest arguments to be used");
509
          return true;
510
        }
511
 
512
      cpp_error (pfile, CPP_DL_ERROR,
513
                 "macro \"%s\" requires %u arguments, but only %u given",
514
                 NODE_NAME (node), macro->paramc, argc);
515
    }
516
  else
517
    cpp_error (pfile, CPP_DL_ERROR,
518
               "macro \"%s\" passed %u arguments, but takes just %u",
519
               NODE_NAME (node), argc, macro->paramc);
520
 
521
  return false;
522
}
523
 
524
/* Reads and returns the arguments to a function-like macro
525
   invocation.  Assumes the opening parenthesis has been processed.
526
   If there is an error, emits an appropriate diagnostic and returns
527
   NULL.  Each argument is terminated by a CPP_EOF token, for the
528
   future benefit of expand_arg().  */
529
static _cpp_buff *
530
collect_args (cpp_reader *pfile, const cpp_hashnode *node)
531
{
532
  _cpp_buff *buff, *base_buff;
533
  cpp_macro *macro;
534
  macro_arg *args, *arg;
535
  const cpp_token *token;
536
  unsigned int argc;
537
 
538
  macro = node->value.macro;
539
  if (macro->paramc)
540
    argc = macro->paramc;
541
  else
542
    argc = 1;
543
  buff = _cpp_get_buff (pfile, argc * (50 * sizeof (cpp_token *)
544
                                       + sizeof (macro_arg)));
545
  base_buff = buff;
546
  args = (macro_arg *) buff->base;
547
  memset (args, 0, argc * sizeof (macro_arg));
548
  buff->cur = (unsigned char *) &args[argc];
549
  arg = args, argc = 0;
550
 
551
  /* Collect the tokens making up each argument.  We don't yet know
552
     how many arguments have been supplied, whether too many or too
553
     few.  Hence the slightly bizarre usage of "argc" and "arg".  */
554
  do
555
    {
556
      unsigned int paren_depth = 0;
557
      unsigned int ntokens = 0;
558
 
559
      argc++;
560
      arg->first = (const cpp_token **) buff->cur;
561
 
562
      for (;;)
563
        {
564
          /* Require space for 2 new tokens (including a CPP_EOF).  */
565
          if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
566
            {
567
              buff = _cpp_append_extend_buff (pfile, buff,
568
                                              1000 * sizeof (cpp_token *));
569
              arg->first = (const cpp_token **) buff->cur;
570
            }
571
 
572
          token = cpp_get_token (pfile);
573
 
574
          if (token->type == CPP_PADDING)
575
            {
576
              /* Drop leading padding.  */
577
              if (ntokens == 0)
578
                continue;
579
            }
580
          else if (token->type == CPP_OPEN_PAREN)
581
            paren_depth++;
582
          else if (token->type == CPP_CLOSE_PAREN)
583
            {
584
              if (paren_depth-- == 0)
585
                break;
586
            }
587
          else if (token->type == CPP_COMMA)
588
            {
589
              /* A comma does not terminate an argument within
590
                 parentheses or as part of a variable argument.  */
591
              if (paren_depth == 0
592
                  && ! (macro->variadic && argc == macro->paramc))
593
                break;
594
            }
595
          else if (token->type == CPP_EOF
596
                   || (token->type == CPP_HASH && token->flags & BOL))
597
            break;
598
 
599
          arg->first[ntokens++] = token;
600
        }
601
 
602
      /* Drop trailing padding.  */
603
      while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
604
        ntokens--;
605
 
606
      arg->count = ntokens;
607
      arg->first[ntokens] = &pfile->eof;
608
 
609
      /* Terminate the argument.  Excess arguments loop back and
610
         overwrite the final legitimate argument, before failing.  */
611
      if (argc <= macro->paramc)
612
        {
613
          buff->cur = (unsigned char *) &arg->first[ntokens + 1];
614
          if (argc != macro->paramc)
615
            arg++;
616
        }
617
    }
618
  while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
619
 
620
  if (token->type == CPP_EOF)
621
    {
622
      /* We still need the CPP_EOF to end directives, and to end
623
         pre-expansion of a macro argument.  Step back is not
624
         unconditional, since we don't want to return a CPP_EOF to our
625
         callers at the end of an -include-d file.  */
626
      if (pfile->context->prev || pfile->state.in_directive)
627
        _cpp_backup_tokens (pfile, 1);
628
      cpp_error (pfile, CPP_DL_ERROR,
629
                 "unterminated argument list invoking macro \"%s\"",
630
                 NODE_NAME (node));
631
    }
632
  else
633
    {
634
      /* A single empty argument is counted as no argument.  */
635
      if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
636
        argc = 0;
637
      if (_cpp_arguments_ok (pfile, macro, node, argc))
638
        {
639
          /* GCC has special semantics for , ## b where b is a varargs
640
             parameter: we remove the comma if b was omitted entirely.
641
             If b was merely an empty argument, the comma is retained.
642
             If the macro takes just one (varargs) parameter, then we
643
             retain the comma only if we are standards conforming.
644
 
645
             If FIRST is NULL replace_args () swallows the comma.  */
646
          if (macro->variadic && (argc < macro->paramc
647
                                  || (argc == 1 && args[0].count == 0
648
                                      && !CPP_OPTION (pfile, std))))
649
            args[macro->paramc - 1].first = NULL;
650
          return base_buff;
651
        }
652
    }
653
 
654
  /* An error occurred.  */
655
  _cpp_release_buff (pfile, base_buff);
656
  return NULL;
657
}
658
 
659
/* Search for an opening parenthesis to the macro of NODE, in such a
660
   way that, if none is found, we don't lose the information in any
661
   intervening padding tokens.  If we find the parenthesis, collect
662
   the arguments and return the buffer containing them.  */
663
static _cpp_buff *
664
funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node)
665
{
666
  const cpp_token *token, *padding = NULL;
667
 
668
  for (;;)
669
    {
670
      token = cpp_get_token (pfile);
671
      if (token->type != CPP_PADDING)
672
        break;
673
      if (padding == NULL
674
          || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
675
        padding = token;
676
    }
677
 
678
  if (token->type == CPP_OPEN_PAREN)
679
    {
680
      pfile->state.parsing_args = 2;
681
      return collect_args (pfile, node);
682
    }
683
 
684
  /* CPP_EOF can be the end of macro arguments, or the end of the
685
     file.  We mustn't back up over the latter.  Ugh.  */
686
  if (token->type != CPP_EOF || token == &pfile->eof)
687
    {
688
      /* Back up.  We may have skipped padding, in which case backing
689
         up more than one token when expanding macros is in general
690
         too difficult.  We re-insert it in its own context.  */
691
      _cpp_backup_tokens (pfile, 1);
692
      if (padding)
693
        push_token_context (pfile, NULL, padding, 1);
694
    }
695
 
696
  return NULL;
697
}
698
 
699
/* Push the context of a macro with hash entry NODE onto the context
700
   stack.  If we can successfully expand the macro, we push a context
701
   containing its yet-to-be-rescanned replacement list and return one.
702
   Otherwise, we don't push a context and return zero.  */
703
static int
704
enter_macro_context (cpp_reader *pfile, cpp_hashnode *node)
705
{
706
  /* The presence of a macro invalidates a file's controlling macro.  */
707
  pfile->mi_valid = false;
708
 
709
  pfile->state.angled_headers = false;
710
 
711
  /* Handle standard macros.  */
712
  if (! (node->flags & NODE_BUILTIN))
713
    {
714
      cpp_macro *macro = node->value.macro;
715
 
716
      if (macro->fun_like)
717
        {
718
          _cpp_buff *buff;
719
 
720
          pfile->state.prevent_expansion++;
721
          pfile->keep_tokens++;
722
          pfile->state.parsing_args = 1;
723
          buff = funlike_invocation_p (pfile, node);
724
          pfile->state.parsing_args = 0;
725
          pfile->keep_tokens--;
726
          pfile->state.prevent_expansion--;
727
 
728
          if (buff == NULL)
729
            {
730
              if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
731
                cpp_error (pfile, CPP_DL_WARNING,
732
 "function-like macro \"%s\" must be used with arguments in traditional C",
733
                           NODE_NAME (node));
734
 
735
              return 0;
736
            }
737
 
738
          if (macro->paramc > 0)
739
            replace_args (pfile, node, macro, (macro_arg *) buff->base);
740
          _cpp_release_buff (pfile, buff);
741
        }
742
 
743
      /* Disable the macro within its expansion.  */
744
      node->flags |= NODE_DISABLED;
745
 
746
      macro->used = 1;
747
 
748
      if (macro->paramc == 0)
749
        push_token_context (pfile, node, macro->exp.tokens, macro->count);
750
 
751
      return 1;
752
    }
753
 
754
  /* Handle built-in macros and the _Pragma operator.  */
755
  return builtin_macro (pfile, node);
756
}
757
 
758
/* Replace the parameters in a function-like macro of NODE with the
759
   actual ARGS, and place the result in a newly pushed token context.
760
   Expand each argument before replacing, unless it is operated upon
761
   by the # or ## operators.  */
762
static void
763
replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro, macro_arg *args)
764
{
765
  unsigned int i, total;
766
  const cpp_token *src, *limit;
767
  const cpp_token **dest, **first;
768
  macro_arg *arg;
769
  _cpp_buff *buff;
770
 
771
  /* First, fully macro-expand arguments, calculating the number of
772
     tokens in the final expansion as we go.  The ordering of the if
773
     statements below is subtle; we must handle stringification before
774
     pasting.  */
775
  total = macro->count;
776
  limit = macro->exp.tokens + macro->count;
777
 
778
  for (src = macro->exp.tokens; src < limit; src++)
779
    if (src->type == CPP_MACRO_ARG)
780
      {
781
        /* Leading and trailing padding tokens.  */
782
        total += 2;
783
 
784
        /* We have an argument.  If it is not being stringified or
785
           pasted it is macro-replaced before insertion.  */
786
        arg = &args[src->val.arg_no - 1];
787
 
788
        if (src->flags & STRINGIFY_ARG)
789
          {
790
            if (!arg->stringified)
791
              arg->stringified = stringify_arg (pfile, arg);
792
          }
793
        else if ((src->flags & PASTE_LEFT)
794
                 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
795
          total += arg->count - 1;
796
        else
797
          {
798
            if (!arg->expanded)
799
              expand_arg (pfile, arg);
800
            total += arg->expanded_count - 1;
801
          }
802
      }
803
 
804
  /* Now allocate space for the expansion, copy the tokens and replace
805
     the arguments.  */
806
  buff = _cpp_get_buff (pfile, total * sizeof (cpp_token *));
807
  first = (const cpp_token **) buff->base;
808
  dest = first;
809
 
810
  for (src = macro->exp.tokens; src < limit; src++)
811
    {
812
      unsigned int count;
813
      const cpp_token **from, **paste_flag;
814
 
815
      if (src->type != CPP_MACRO_ARG)
816
        {
817
          *dest++ = src;
818
          continue;
819
        }
820
 
821
      paste_flag = 0;
822
      arg = &args[src->val.arg_no - 1];
823
      if (src->flags & STRINGIFY_ARG)
824
        count = 1, from = &arg->stringified;
825
      else if (src->flags & PASTE_LEFT)
826
        count = arg->count, from = arg->first;
827
      else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
828
        {
829
          count = arg->count, from = arg->first;
830
          if (dest != first)
831
            {
832
              if (dest[-1]->type == CPP_COMMA
833
                  && macro->variadic
834
                  && src->val.arg_no == macro->paramc)
835
                {
836
                  /* Swallow a pasted comma if from == NULL, otherwise
837
                     drop the paste flag.  */
838
                  if (from == NULL)
839
                    dest--;
840
                  else
841
                    paste_flag = dest - 1;
842
                }
843
              /* Remove the paste flag if the RHS is a placemarker.  */
844
              else if (count == 0)
845
                paste_flag = dest - 1;
846
            }
847
        }
848
      else
849
        count = arg->expanded_count, from = arg->expanded;
850
 
851
      /* Padding on the left of an argument (unless RHS of ##).  */
852
      if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
853
          && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
854
        *dest++ = padding_token (pfile, src);
855
 
856
      if (count)
857
        {
858
          memcpy (dest, from, count * sizeof (cpp_token *));
859
          dest += count;
860
 
861
          /* With a non-empty argument on the LHS of ##, the last
862
             token should be flagged PASTE_LEFT.  */
863
          if (src->flags & PASTE_LEFT)
864
            paste_flag = dest - 1;
865
        }
866
 
867
      /* Avoid paste on RHS (even case count == 0).  */
868
      if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
869
        *dest++ = &pfile->avoid_paste;
870
 
871
      /* Add a new paste flag, or remove an unwanted one.  */
872
      if (paste_flag)
873
        {
874
          cpp_token *token = _cpp_temp_token (pfile);
875
          token->type = (*paste_flag)->type;
876
          token->val = (*paste_flag)->val;
877
          if (src->flags & PASTE_LEFT)
878
            token->flags = (*paste_flag)->flags | PASTE_LEFT;
879
          else
880
            token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
881
          *paste_flag = token;
882
        }
883
    }
884
 
885
  /* Free the expanded arguments.  */
886
  for (i = 0; i < macro->paramc; i++)
887
    if (args[i].expanded)
888
      free (args[i].expanded);
889
 
890
  push_ptoken_context (pfile, node, buff, first, dest - first);
891
}
892
 
893
/* Return a special padding token, with padding inherited from SOURCE.  */
894
static const cpp_token *
895
padding_token (cpp_reader *pfile, const cpp_token *source)
896
{
897
  cpp_token *result = _cpp_temp_token (pfile);
898
 
899
  result->type = CPP_PADDING;
900
 
901
  /* Data in GCed data structures cannot be made const so far, so we
902
     need a cast here.  */
903
  result->val.source = (cpp_token *) source;
904
  result->flags = 0;
905
  return result;
906
}
907
 
908
/* Get a new uninitialized context.  Create a new one if we cannot
909
   re-use an old one.  */
910
static cpp_context *
911
next_context (cpp_reader *pfile)
912
{
913
  cpp_context *result = pfile->context->next;
914
 
915
  if (result == 0)
916
    {
917
      result = XNEW (cpp_context);
918
      result->prev = pfile->context;
919
      result->next = 0;
920
      pfile->context->next = result;
921
    }
922
 
923
  pfile->context = result;
924
  return result;
925
}
926
 
927
/* Push a list of pointers to tokens.  */
928
static void
929
push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
930
                     const cpp_token **first, unsigned int count)
931
{
932
  cpp_context *context = next_context (pfile);
933
 
934
  context->direct_p = false;
935
  context->macro = macro;
936
  context->buff = buff;
937
  FIRST (context).ptoken = first;
938
  LAST (context).ptoken = first + count;
939
}
940
 
941
/* Push a list of tokens.  */
942
static void
943
push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
944
                    const cpp_token *first, unsigned int count)
945
{
946
  cpp_context *context = next_context (pfile);
947
 
948
  context->direct_p = true;
949
  context->macro = macro;
950
  context->buff = NULL;
951
  FIRST (context).token = first;
952
  LAST (context).token = first + count;
953
}
954
 
955
/* Push a traditional macro's replacement text.  */
956
void
957
_cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
958
                        const uchar *start, size_t len)
959
{
960
  cpp_context *context = next_context (pfile);
961
 
962
  context->direct_p = true;
963
  context->macro = macro;
964
  context->buff = NULL;
965
  CUR (context) = start;
966
  RLIMIT (context) = start + len;
967
  macro->flags |= NODE_DISABLED;
968
}
969
 
970
/* Expand an argument ARG before replacing parameters in a
971
   function-like macro.  This works by pushing a context with the
972
   argument's tokens, and then expanding that into a temporary buffer
973
   as if it were a normal part of the token stream.  collect_args()
974
   has terminated the argument's tokens with a CPP_EOF so that we know
975
   when we have fully expanded the argument.  */
976
static void
977
expand_arg (cpp_reader *pfile, macro_arg *arg)
978
{
979
  unsigned int capacity;
980
  bool saved_warn_trad;
981
 
982
  if (arg->count == 0)
983
    return;
984
 
985
  /* Don't warn about funlike macros when pre-expanding.  */
986
  saved_warn_trad = CPP_WTRADITIONAL (pfile);
987
  CPP_WTRADITIONAL (pfile) = 0;
988
 
989
  /* Loop, reading in the arguments.  */
990
  capacity = 256;
991
  arg->expanded = XNEWVEC (const cpp_token *, capacity);
992
 
993
  push_ptoken_context (pfile, NULL, NULL, arg->first, arg->count + 1);
994
  for (;;)
995
    {
996
      const cpp_token *token;
997
 
998
      if (arg->expanded_count + 1 >= capacity)
999
        {
1000
          capacity *= 2;
1001
          arg->expanded = XRESIZEVEC (const cpp_token *, arg->expanded,
1002
                                      capacity);
1003
        }
1004
 
1005
      token = cpp_get_token (pfile);
1006
 
1007
      if (token->type == CPP_EOF)
1008
        break;
1009
 
1010
      arg->expanded[arg->expanded_count++] = token;
1011
    }
1012
 
1013
  _cpp_pop_context (pfile);
1014
 
1015
  CPP_WTRADITIONAL (pfile) = saved_warn_trad;
1016
}
1017
 
1018
/* Pop the current context off the stack, re-enabling the macro if the
1019
   context represented a macro's replacement list.  The context
1020
   structure is not freed so that we can re-use it later.  */
1021
void
1022
_cpp_pop_context (cpp_reader *pfile)
1023
{
1024
  cpp_context *context = pfile->context;
1025
 
1026
  if (context->macro)
1027
    context->macro->flags &= ~NODE_DISABLED;
1028
 
1029
  if (context->buff)
1030
    _cpp_release_buff (pfile, context->buff);
1031
 
1032
  pfile->context = context->prev;
1033
}
1034
 
1035
/* External routine to get a token.  Also used nearly everywhere
1036
   internally, except for places where we know we can safely call
1037
   _cpp_lex_token directly, such as lexing a directive name.
1038
 
1039
   Macro expansions and directives are transparently handled,
1040
   including entering included files.  Thus tokens are post-macro
1041
   expansion, and after any intervening directives.  External callers
1042
   see CPP_EOF only at EOF.  Internal callers also see it when meeting
1043
   a directive inside a macro call, when at the end of a directive and
1044
   state.in_directive is still 1, and at the end of argument
1045
   pre-expansion.  */
1046
const cpp_token *
1047
cpp_get_token (cpp_reader *pfile)
1048
{
1049
  const cpp_token *result;
1050
 
1051
  for (;;)
1052
    {
1053
      cpp_hashnode *node;
1054
      cpp_context *context = pfile->context;
1055
 
1056
      /* Context->prev == 0 <=> base context.  */
1057
      if (!context->prev)
1058
        result = _cpp_lex_token (pfile);
1059
      else if (FIRST (context).token != LAST (context).token)
1060
        {
1061
          if (context->direct_p)
1062
            result = FIRST (context).token++;
1063
          else
1064
            result = *FIRST (context).ptoken++;
1065
 
1066
          if (result->flags & PASTE_LEFT)
1067
            {
1068
              paste_all_tokens (pfile, result);
1069
              if (pfile->state.in_directive)
1070
                continue;
1071
              return padding_token (pfile, result);
1072
            }
1073
        }
1074
      else
1075
        {
1076
          _cpp_pop_context (pfile);
1077
          if (pfile->state.in_directive)
1078
            continue;
1079
          return &pfile->avoid_paste;
1080
        }
1081
 
1082
      if (pfile->state.in_directive && result->type == CPP_COMMENT)
1083
        continue;
1084
 
1085
      if (result->type != CPP_NAME)
1086
        break;
1087
 
1088
      node = result->val.node;
1089
 
1090
      if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
1091
        break;
1092
 
1093
      if (!(node->flags & NODE_DISABLED))
1094
        {
1095
          if (!pfile->state.prevent_expansion
1096
              && enter_macro_context (pfile, node))
1097
            {
1098
              if (pfile->state.in_directive)
1099
                continue;
1100
              return padding_token (pfile, result);
1101
            }
1102
        }
1103
      else
1104
        {
1105
          /* Flag this token as always unexpandable.  FIXME: move this
1106
             to collect_args()?.  */
1107
          cpp_token *t = _cpp_temp_token (pfile);
1108
          t->type = result->type;
1109
          t->flags = result->flags | NO_EXPAND;
1110
          t->val = result->val;
1111
          result = t;
1112
        }
1113
 
1114
      break;
1115
    }
1116
 
1117
  return result;
1118
}
1119
 
1120
/* Returns true if we're expanding an object-like macro that was
1121
   defined in a system header.  Just checks the macro at the top of
1122
   the stack.  Used for diagnostic suppression.  */
1123
int
1124
cpp_sys_macro_p (cpp_reader *pfile)
1125
{
1126
  cpp_hashnode *node = pfile->context->macro;
1127
 
1128
  return node && node->value.macro && node->value.macro->syshdr;
1129
}
1130
 
1131
/* Read each token in, until end of the current file.  Directives are
1132
   transparently processed.  */
1133
void
1134
cpp_scan_nooutput (cpp_reader *pfile)
1135
{
1136
  /* Request a CPP_EOF token at the end of this file, rather than
1137
     transparently continuing with the including file.  */
1138
  pfile->buffer->return_at_eof = true;
1139
 
1140
  pfile->state.discarding_output++;
1141
  pfile->state.prevent_expansion++;
1142
 
1143
  if (CPP_OPTION (pfile, traditional))
1144
    while (_cpp_read_logical_line_trad (pfile))
1145
      ;
1146
  else
1147
    while (cpp_get_token (pfile)->type != CPP_EOF)
1148
      ;
1149
 
1150
  pfile->state.discarding_output--;
1151
  pfile->state.prevent_expansion--;
1152
}
1153
 
1154
/* Step back one (or more) tokens.  Can only step mack more than 1 if
1155
   they are from the lexer, and not from macro expansion.  */
1156
void
1157
_cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
1158
{
1159
  if (pfile->context->prev == NULL)
1160
    {
1161
      pfile->lookaheads += count;
1162
      while (count--)
1163
        {
1164
          pfile->cur_token--;
1165
          if (pfile->cur_token == pfile->cur_run->base
1166
              /* Possible with -fpreprocessed and no leading #line.  */
1167
              && pfile->cur_run->prev != NULL)
1168
            {
1169
              pfile->cur_run = pfile->cur_run->prev;
1170
              pfile->cur_token = pfile->cur_run->limit;
1171
            }
1172
        }
1173
    }
1174
  else
1175
    {
1176
      if (count != 1)
1177
        abort ();
1178
      if (pfile->context->direct_p)
1179
        FIRST (pfile->context).token--;
1180
      else
1181
        FIRST (pfile->context).ptoken--;
1182
    }
1183
}
1184
 
1185
/* #define directive parsing and handling.  */
1186
 
1187
/* Returns nonzero if a macro redefinition warning is required.  */
1188
static bool
1189
warn_of_redefinition (cpp_reader *pfile, const cpp_hashnode *node,
1190
                      const cpp_macro *macro2)
1191
{
1192
  const cpp_macro *macro1;
1193
  unsigned int i;
1194
 
1195
  /* Some redefinitions need to be warned about regardless.  */
1196
  if (node->flags & NODE_WARN)
1197
    return true;
1198
 
1199
  /* Redefinition of a macro is allowed if and only if the old and new
1200
     definitions are the same.  (6.10.3 paragraph 2).  */
1201
  macro1 = node->value.macro;
1202
 
1203
  /* Don't check count here as it can be different in valid
1204
     traditional redefinitions with just whitespace differences.  */
1205
  if (macro1->paramc != macro2->paramc
1206
      || macro1->fun_like != macro2->fun_like
1207
      || macro1->variadic != macro2->variadic)
1208
    return true;
1209
 
1210
  /* Check parameter spellings.  */
1211
  for (i = 0; i < macro1->paramc; i++)
1212
    if (macro1->params[i] != macro2->params[i])
1213
      return true;
1214
 
1215
  /* Check the replacement text or tokens.  */
1216
  if (CPP_OPTION (pfile, traditional))
1217
    return _cpp_expansions_different_trad (macro1, macro2);
1218
 
1219
  if (macro1->count != macro2->count)
1220
    return true;
1221
 
1222
  for (i = 0; i < macro1->count; i++)
1223
    if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
1224
      return true;
1225
 
1226
  return false;
1227
}
1228
 
1229
/* Free the definition of hashnode H.  */
1230
void
1231
_cpp_free_definition (cpp_hashnode *h)
1232
{
1233
  /* Macros and assertions no longer have anything to free.  */
1234
  h->type = NT_VOID;
1235
  /* Clear builtin flag in case of redefinition.  */
1236
  h->flags &= ~(NODE_BUILTIN | NODE_DISABLED);
1237
}
1238
 
1239
/* Save parameter NODE to the parameter list of macro MACRO.  Returns
1240
   zero on success, nonzero if the parameter is a duplicate.  */
1241
bool
1242
_cpp_save_parameter (cpp_reader *pfile, cpp_macro *macro, cpp_hashnode *node)
1243
{
1244
  unsigned int len;
1245
  /* Constraint 6.10.3.6 - duplicate parameter names.  */
1246
  if (node->flags & NODE_MACRO_ARG)
1247
    {
1248
      cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
1249
                 NODE_NAME (node));
1250
      return true;
1251
    }
1252
 
1253
  if (BUFF_ROOM (pfile->a_buff)
1254
      < (macro->paramc + 1) * sizeof (cpp_hashnode *))
1255
    _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
1256
 
1257
  ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = node;
1258
  node->flags |= NODE_MACRO_ARG;
1259
  len = macro->paramc * sizeof (union _cpp_hashnode_value);
1260
  if (len > pfile->macro_buffer_len)
1261
    {
1262
      pfile->macro_buffer = XRESIZEVEC (unsigned char, pfile->macro_buffer,
1263
                                        len);
1264
      pfile->macro_buffer_len = len;
1265
    }
1266
  ((union _cpp_hashnode_value *) pfile->macro_buffer)[macro->paramc - 1]
1267
    = node->value;
1268
 
1269
  node->value.arg_index  = macro->paramc;
1270
  return false;
1271
}
1272
 
1273
/* Check the syntax of the parameters in a MACRO definition.  Returns
1274
   false if an error occurs.  */
1275
static bool
1276
parse_params (cpp_reader *pfile, cpp_macro *macro)
1277
{
1278
  unsigned int prev_ident = 0;
1279
 
1280
  for (;;)
1281
    {
1282
      const cpp_token *token = _cpp_lex_token (pfile);
1283
 
1284
      switch (token->type)
1285
        {
1286
        default:
1287
          /* Allow/ignore comments in parameter lists if we are
1288
             preserving comments in macro expansions.  */
1289
          if (token->type == CPP_COMMENT
1290
              && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
1291
            continue;
1292
 
1293
          cpp_error (pfile, CPP_DL_ERROR,
1294
                     "\"%s\" may not appear in macro parameter list",
1295
                     cpp_token_as_text (pfile, token));
1296
          return false;
1297
 
1298
        case CPP_NAME:
1299
          if (prev_ident)
1300
            {
1301
              cpp_error (pfile, CPP_DL_ERROR,
1302
                         "macro parameters must be comma-separated");
1303
              return false;
1304
            }
1305
          prev_ident = 1;
1306
 
1307
          if (_cpp_save_parameter (pfile, macro, token->val.node))
1308
            return false;
1309
          continue;
1310
 
1311
        case CPP_CLOSE_PAREN:
1312
          if (prev_ident || macro->paramc == 0)
1313
            return true;
1314
 
1315
          /* Fall through to pick up the error.  */
1316
        case CPP_COMMA:
1317
          if (!prev_ident)
1318
            {
1319
              cpp_error (pfile, CPP_DL_ERROR, "parameter name missing");
1320
              return false;
1321
            }
1322
          prev_ident = 0;
1323
          continue;
1324
 
1325
        case CPP_ELLIPSIS:
1326
          macro->variadic = 1;
1327
          if (!prev_ident)
1328
            {
1329
              _cpp_save_parameter (pfile, macro,
1330
                                   pfile->spec_nodes.n__VA_ARGS__);
1331
              pfile->state.va_args_ok = 1;
1332
              if (! CPP_OPTION (pfile, c99)
1333
                  && CPP_OPTION (pfile, pedantic)
1334
                  && CPP_OPTION (pfile, warn_variadic_macros))
1335
                cpp_error (pfile, CPP_DL_PEDWARN,
1336
                           "anonymous variadic macros were introduced in C99");
1337
            }
1338
          else if (CPP_OPTION (pfile, pedantic)
1339
                   && CPP_OPTION (pfile, warn_variadic_macros))
1340
            cpp_error (pfile, CPP_DL_PEDWARN,
1341
                       "ISO C does not permit named variadic macros");
1342
 
1343
          /* We're at the end, and just expect a closing parenthesis.  */
1344
          token = _cpp_lex_token (pfile);
1345
          if (token->type == CPP_CLOSE_PAREN)
1346
            return true;
1347
          /* Fall through.  */
1348
 
1349
        case CPP_EOF:
1350
          cpp_error (pfile, CPP_DL_ERROR, "missing ')' in macro parameter list");
1351
          return false;
1352
        }
1353
    }
1354
}
1355
 
1356
/* Allocate room for a token from a macro's replacement list.  */
1357
static cpp_token *
1358
alloc_expansion_token (cpp_reader *pfile, cpp_macro *macro)
1359
{
1360
  if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
1361
    _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
1362
 
1363
  return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
1364
}
1365
 
1366
/* Lex a token from the expansion of MACRO, but mark parameters as we
1367
   find them and warn of traditional stringification.  */
1368
static cpp_token *
1369
lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
1370
{
1371
  cpp_token *token;
1372
 
1373
  pfile->cur_token = alloc_expansion_token (pfile, macro);
1374
  token = _cpp_lex_direct (pfile);
1375
 
1376
  /* Is this a parameter?  */
1377
  if (token->type == CPP_NAME
1378
      && (token->val.node->flags & NODE_MACRO_ARG) != 0)
1379
    {
1380
      token->type = CPP_MACRO_ARG;
1381
      token->val.arg_no = token->val.node->value.arg_index;
1382
    }
1383
  else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
1384
           && (token->type == CPP_STRING || token->type == CPP_CHAR))
1385
    check_trad_stringification (pfile, macro, &token->val.str);
1386
 
1387
  return token;
1388
}
1389
 
1390
static bool
1391
create_iso_definition (cpp_reader *pfile, cpp_macro *macro)
1392
{
1393
  cpp_token *token;
1394
  const cpp_token *ctoken;
1395
 
1396
  /* Get the first token of the expansion (or the '(' of a
1397
     function-like macro).  */
1398
  ctoken = _cpp_lex_token (pfile);
1399
 
1400
  if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
1401
    {
1402
      bool ok = parse_params (pfile, macro);
1403
      macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
1404
      if (!ok)
1405
        return false;
1406
 
1407
      /* Success.  Commit or allocate the parameter array.  */
1408
      if (pfile->hash_table->alloc_subobject)
1409
        {
1410
          cpp_hashnode **params =
1411
            (cpp_hashnode **) pfile->hash_table->alloc_subobject
1412
            (sizeof (cpp_hashnode *) * macro->paramc);
1413
          memcpy (params, macro->params,
1414
                  sizeof (cpp_hashnode *) * macro->paramc);
1415
          macro->params = params;
1416
        }
1417
      else
1418
        BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
1419
      macro->fun_like = 1;
1420
    }
1421
  else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
1422
    {
1423
      /* While ISO C99 requires whitespace before replacement text
1424
         in a macro definition, ISO C90 with TC1 allows there characters
1425
         from the basic source character set.  */
1426
      if (CPP_OPTION (pfile, c99))
1427
        cpp_error (pfile, CPP_DL_PEDWARN,
1428
                   "ISO C99 requires whitespace after the macro name");
1429
      else
1430
        {
1431
          int warntype = CPP_DL_WARNING;
1432
          switch (ctoken->type)
1433
            {
1434
            case CPP_ATSIGN:
1435
            case CPP_AT_NAME:
1436
            case CPP_OBJC_STRING:
1437
              /* '@' is not in basic character set.  */
1438
              warntype = CPP_DL_PEDWARN;
1439
              break;
1440
            case CPP_OTHER:
1441
              /* Basic character set sans letters, digits and _.  */
1442
              if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
1443
                          ctoken->val.str.text[0]) == NULL)
1444
                warntype = CPP_DL_PEDWARN;
1445
              break;
1446
            default:
1447
              /* All other tokens start with a character from basic
1448
                 character set.  */
1449
              break;
1450
            }
1451
          cpp_error (pfile, warntype,
1452
                     "missing whitespace after the macro name");
1453
        }
1454
    }
1455
 
1456
  if (macro->fun_like)
1457
    token = lex_expansion_token (pfile, macro);
1458
  else
1459
    {
1460
      token = alloc_expansion_token (pfile, macro);
1461
      *token = *ctoken;
1462
    }
1463
 
1464
  for (;;)
1465
    {
1466
      /* Check the stringifying # constraint 6.10.3.2.1 of
1467
         function-like macros when lexing the subsequent token.  */
1468
      if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
1469
        {
1470
          if (token->type == CPP_MACRO_ARG)
1471
            {
1472
              token->flags &= ~PREV_WHITE;
1473
              token->flags |= STRINGIFY_ARG;
1474
              token->flags |= token[-1].flags & PREV_WHITE;
1475
              token[-1] = token[0];
1476
              macro->count--;
1477
            }
1478
          /* Let assembler get away with murder.  */
1479
          else if (CPP_OPTION (pfile, lang) != CLK_ASM)
1480
            {
1481
              cpp_error (pfile, CPP_DL_ERROR,
1482
                         "'#' is not followed by a macro parameter");
1483
              return false;
1484
            }
1485
        }
1486
 
1487
      if (token->type == CPP_EOF)
1488
        break;
1489
 
1490
      /* Paste operator constraint 6.10.3.3.1.  */
1491
      if (token->type == CPP_PASTE)
1492
        {
1493
          /* Token-paste ##, can appear in both object-like and
1494
             function-like macros, but not at the ends.  */
1495
          if (--macro->count > 0)
1496
            token = lex_expansion_token (pfile, macro);
1497
 
1498
          if (macro->count == 0 || token->type == CPP_EOF)
1499
            {
1500
              cpp_error (pfile, CPP_DL_ERROR,
1501
                 "'##' cannot appear at either end of a macro expansion");
1502
              return false;
1503
            }
1504
 
1505
          token[-1].flags |= PASTE_LEFT;
1506
        }
1507
 
1508
      token = lex_expansion_token (pfile, macro);
1509
    }
1510
 
1511
  macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
1512
  macro->traditional = 0;
1513
 
1514
  /* Don't count the CPP_EOF.  */
1515
  macro->count--;
1516
 
1517
  /* Clear whitespace on first token for warn_of_redefinition().  */
1518
  if (macro->count)
1519
    macro->exp.tokens[0].flags &= ~PREV_WHITE;
1520
 
1521
  /* Commit or allocate the memory.  */
1522
  if (pfile->hash_table->alloc_subobject)
1523
    {
1524
      cpp_token *tokns =
1525
        (cpp_token *) pfile->hash_table->alloc_subobject (sizeof (cpp_token)
1526
                                                          * macro->count);
1527
      memcpy (tokns, macro->exp.tokens, sizeof (cpp_token) * macro->count);
1528
      macro->exp.tokens = tokns;
1529
    }
1530
  else
1531
    BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
1532
 
1533
  return true;
1534
}
1535
 
1536
/* Parse a macro and save its expansion.  Returns nonzero on success.  */
1537
bool
1538
_cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
1539
{
1540
  cpp_macro *macro;
1541
  unsigned int i;
1542
  bool ok;
1543
 
1544
  if (pfile->hash_table->alloc_subobject)
1545
    macro = (cpp_macro *) pfile->hash_table->alloc_subobject
1546
      (sizeof (cpp_macro));
1547
  else
1548
    macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
1549
  macro->line = pfile->directive_line;
1550
  macro->params = 0;
1551
  macro->paramc = 0;
1552
  macro->variadic = 0;
1553
  macro->used = !CPP_OPTION (pfile, warn_unused_macros);
1554
  macro->count = 0;
1555
  macro->fun_like = 0;
1556
  /* To suppress some diagnostics.  */
1557
  macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
1558
 
1559
  if (CPP_OPTION (pfile, traditional))
1560
    ok = _cpp_create_trad_definition (pfile, macro);
1561
  else
1562
    {
1563
      cpp_token *saved_cur_token = pfile->cur_token;
1564
 
1565
      ok = create_iso_definition (pfile, macro);
1566
 
1567
      /* Restore lexer position because of games lex_expansion_token()
1568
         plays lexing the macro.  We set the type for SEEN_EOL() in
1569
         directives.c.
1570
 
1571
         Longer term we should lex the whole line before coming here,
1572
         and just copy the expansion.  */
1573
      saved_cur_token[-1].type = pfile->cur_token[-1].type;
1574
      pfile->cur_token = saved_cur_token;
1575
 
1576
      /* Stop the lexer accepting __VA_ARGS__.  */
1577
      pfile->state.va_args_ok = 0;
1578
    }
1579
 
1580
  /* Clear the fast argument lookup indices.  */
1581
  for (i = macro->paramc; i-- > 0; )
1582
    {
1583
      struct cpp_hashnode *node = macro->params[i];
1584
      node->flags &= ~ NODE_MACRO_ARG;
1585
      node->value = ((union _cpp_hashnode_value *) pfile->macro_buffer)[i];
1586
    }
1587
 
1588
  if (!ok)
1589
    return ok;
1590
 
1591
  if (node->type == NT_MACRO)
1592
    {
1593
      if (CPP_OPTION (pfile, warn_unused_macros))
1594
        _cpp_warn_if_unused_macro (pfile, node, NULL);
1595
 
1596
      if (warn_of_redefinition (pfile, node, macro))
1597
        {
1598
          cpp_error_with_line (pfile, CPP_DL_PEDWARN, pfile->directive_line, 0,
1599
                               "\"%s\" redefined", NODE_NAME (node));
1600
 
1601
          if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
1602
            cpp_error_with_line (pfile, CPP_DL_PEDWARN,
1603
                                 node->value.macro->line, 0,
1604
                         "this is the location of the previous definition");
1605
        }
1606
    }
1607
 
1608
  if (node->type != NT_VOID)
1609
    _cpp_free_definition (node);
1610
 
1611
  /* Enter definition in hash table.  */
1612
  node->type = NT_MACRO;
1613
  node->value.macro = macro;
1614
  if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_")))
1615
    node->flags |= NODE_WARN;
1616
 
1617
  return ok;
1618
}
1619
 
1620
/* Warn if a token in STRING matches one of a function-like MACRO's
1621
   parameters.  */
1622
static void
1623
check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
1624
                            const cpp_string *string)
1625
{
1626
  unsigned int i, len;
1627
  const uchar *p, *q, *limit;
1628
 
1629
  /* Loop over the string.  */
1630
  limit = string->text + string->len - 1;
1631
  for (p = string->text + 1; p < limit; p = q)
1632
    {
1633
      /* Find the start of an identifier.  */
1634
      while (p < limit && !is_idstart (*p))
1635
        p++;
1636
 
1637
      /* Find the end of the identifier.  */
1638
      q = p;
1639
      while (q < limit && is_idchar (*q))
1640
        q++;
1641
 
1642
      len = q - p;
1643
 
1644
      /* Loop over the function macro arguments to see if the
1645
         identifier inside the string matches one of them.  */
1646
      for (i = 0; i < macro->paramc; i++)
1647
        {
1648
          const cpp_hashnode *node = macro->params[i];
1649
 
1650
          if (NODE_LEN (node) == len
1651
              && !memcmp (p, NODE_NAME (node), len))
1652
            {
1653
              cpp_error (pfile, CPP_DL_WARNING,
1654
           "macro argument \"%s\" would be stringified in traditional C",
1655
                         NODE_NAME (node));
1656
              break;
1657
            }
1658
        }
1659
    }
1660
}
1661
 
1662
/* Returns the name, arguments and expansion of a macro, in a format
1663
   suitable to be read back in again, and therefore also for DWARF 2
1664
   debugging info.  e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
1665
   Caller is expected to generate the "#define" bit if needed.  The
1666
   returned text is temporary, and automatically freed later.  */
1667
const unsigned char *
1668
cpp_macro_definition (cpp_reader *pfile, const cpp_hashnode *node)
1669
{
1670
  unsigned int i, len;
1671
  const cpp_macro *macro = node->value.macro;
1672
  unsigned char *buffer;
1673
 
1674
  if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
1675
    {
1676
      cpp_error (pfile, CPP_DL_ICE,
1677
                 "invalid hash type %d in cpp_macro_definition", node->type);
1678
      return 0;
1679
    }
1680
 
1681
  /* Calculate length.  */
1682
  len = NODE_LEN (node) + 2;                    /* ' ' and NUL.  */
1683
  if (macro->fun_like)
1684
    {
1685
      len += 4;         /* "()" plus possible final ".." of named
1686
                           varargs (we have + 1 below).  */
1687
      for (i = 0; i < macro->paramc; i++)
1688
        len += NODE_LEN (macro->params[i]) + 1; /* "," */
1689
    }
1690
 
1691
  /* This should match below where we fill in the buffer.  */
1692
  if (CPP_OPTION (pfile, traditional))
1693
    len += _cpp_replacement_text_len (macro);
1694
  else
1695
    {
1696
      for (i = 0; i < macro->count; i++)
1697
        {
1698
          cpp_token *token = &macro->exp.tokens[i];
1699
 
1700
          if (token->type == CPP_MACRO_ARG)
1701
            len += NODE_LEN (macro->params[token->val.arg_no - 1]);
1702
          else
1703
            len += cpp_token_len (token);
1704
 
1705
          if (token->flags & STRINGIFY_ARG)
1706
            len++;                      /* "#" */
1707
          if (token->flags & PASTE_LEFT)
1708
            len += 3;           /* " ##" */
1709
          if (token->flags & PREV_WHITE)
1710
            len++;              /* " " */
1711
        }
1712
    }
1713
 
1714
  if (len > pfile->macro_buffer_len)
1715
    {
1716
      pfile->macro_buffer = XRESIZEVEC (unsigned char,
1717
                                        pfile->macro_buffer, len);
1718
      pfile->macro_buffer_len = len;
1719
    }
1720
 
1721
  /* Fill in the buffer.  Start with the macro name.  */
1722
  buffer = pfile->macro_buffer;
1723
  memcpy (buffer, NODE_NAME (node), NODE_LEN (node));
1724
  buffer += NODE_LEN (node);
1725
 
1726
  /* Parameter names.  */
1727
  if (macro->fun_like)
1728
    {
1729
      *buffer++ = '(';
1730
      for (i = 0; i < macro->paramc; i++)
1731
        {
1732
          cpp_hashnode *param = macro->params[i];
1733
 
1734
          if (param != pfile->spec_nodes.n__VA_ARGS__)
1735
            {
1736
              memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
1737
              buffer += NODE_LEN (param);
1738
            }
1739
 
1740
          if (i + 1 < macro->paramc)
1741
            /* Don't emit a space after the comma here; we're trying
1742
               to emit a Dwarf-friendly definition, and the Dwarf spec
1743
               forbids spaces in the argument list.  */
1744
            *buffer++ = ',';
1745
          else if (macro->variadic)
1746
            *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
1747
        }
1748
      *buffer++ = ')';
1749
    }
1750
 
1751
  /* The Dwarf spec requires a space after the macro name, even if the
1752
     definition is the empty string.  */
1753
  *buffer++ = ' ';
1754
 
1755
  if (CPP_OPTION (pfile, traditional))
1756
    buffer = _cpp_copy_replacement_text (macro, buffer);
1757
  else if (macro->count)
1758
  /* Expansion tokens.  */
1759
    {
1760
      for (i = 0; i < macro->count; i++)
1761
        {
1762
          cpp_token *token = &macro->exp.tokens[i];
1763
 
1764
          if (token->flags & PREV_WHITE)
1765
            *buffer++ = ' ';
1766
          if (token->flags & STRINGIFY_ARG)
1767
            *buffer++ = '#';
1768
 
1769
          if (token->type == CPP_MACRO_ARG)
1770
            {
1771
              memcpy (buffer,
1772
                      NODE_NAME (macro->params[token->val.arg_no - 1]),
1773
                      NODE_LEN (macro->params[token->val.arg_no - 1]));
1774
              buffer += NODE_LEN (macro->params[token->val.arg_no - 1]);
1775
            }
1776
          else
1777
            buffer = cpp_spell_token (pfile, token, buffer, false);
1778
 
1779
          if (token->flags & PASTE_LEFT)
1780
            {
1781
              *buffer++ = ' ';
1782
              *buffer++ = '#';
1783
              *buffer++ = '#';
1784
              /* Next has PREV_WHITE; see _cpp_create_definition.  */
1785
            }
1786
        }
1787
    }
1788
 
1789
  *buffer = '\0';
1790
  return pfile->macro_buffer;
1791
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.