OSDN Git Service

* final.c (rest_of_clean_state): Use %m in errors instead of
[pf3gnuchains/gcc-fork.git] / gcc / fortran / cpp.c
1 /* Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
2
3 This file is part of GCC.
4
5 GCC is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License as published by the Free
7 Software Foundation; either version 3, or (at your option) any later
8 version.
9
10 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GCC; see the file COPYING3.  If not see
17 <http://www.gnu.org/licenses/>.  */
18
19 #include "config.h"
20 #include "system.h"
21 #include "coretypes.h"
22 #include "tm.h"
23 #include "tree.h"
24 #include "version.h"
25 #include "flags.h"
26
27
28 #include "options.h"
29 #include "gfortran.h"
30 #include "tm_p.h"               /* Target prototypes.  */
31 #include "target.h"
32 #include "toplev.h"
33 #include "diagnostic.h"
34
35 #include "../../libcpp/internal.h"
36 #include "cpp.h"
37 #include "incpath.h"
38
39 #ifndef TARGET_OS_CPP_BUILTINS
40 # define TARGET_OS_CPP_BUILTINS()
41 #endif
42
43 #ifndef TARGET_OBJFMT_CPP_BUILTINS
44 # define TARGET_OBJFMT_CPP_BUILTINS()
45 #endif
46
47
48 /* Holds switches parsed by gfc_cpp_handle_option (), but whose
49    handling is deferred to gfc_cpp_init ().  */
50 typedef struct
51 {
52     enum opt_code code;
53     const char *arg;
54 }
55 gfc_cpp_deferred_opt_t;
56
57
58 /* Defined and undefined macros being queued for output with -dU at
59    the next newline.  */
60 typedef struct gfc_cpp_macro_queue
61 {
62   struct gfc_cpp_macro_queue *next;     /* Next macro in the list.  */
63   char *macro;                          /* The name of the macro if not
64                                            defined, the full definition if
65                                            defined.  */
66 } gfc_cpp_macro_queue;
67 static gfc_cpp_macro_queue *cpp_define_queue, *cpp_undefine_queue;
68
69 struct gfc_cpp_option_data
70 {
71   /* Argument of -cpp, implied by SPEC;
72      if NULL, preprocessing disabled.  */
73   const char *temporary_filename;
74
75   const char *output_filename;          /* -o <arg>  */
76   int preprocess_only;                  /* -E  */
77   int discard_comments;                 /* -C  */
78   int discard_comments_in_macro_exp;    /* -CC  */
79   int print_include_names;              /* -H  */
80   int no_line_commands;                 /* -P  */
81   char dump_macros;                     /* -d[DMNU]  */
82   int dump_includes;                    /* -dI  */
83   int working_directory;                /* -fworking-directory  */
84   int no_predefined;                    /* -undef */
85   int standard_include_paths;           /* -nostdinc */
86   int verbose;                          /* -v */
87
88   const char *multilib;                 /* -imultilib <dir>  */
89   const char *prefix;                   /* -iprefix <dir>  */
90   const char *sysroot;                  /* -isysroot <dir>  */
91
92   /* Options whose handling needs to be deferred until the
93      appropriate cpp-objects are created:
94       -A predicate=answer
95       -D <macro>[=<val>]
96       -U <macro>  */
97   gfc_cpp_deferred_opt_t *deferred_opt;
98   int deferred_opt_count;
99 }
100 gfc_cpp_option;
101
102 /* Structures used with libcpp:  */
103 static cpp_options *cpp_option = NULL;
104 static cpp_reader *cpp_in = NULL;
105
106 /* Defined in toplev.c.  */
107 extern const char *asm_file_name;
108
109
110
111
112 /* Encapsulates state used to convert a stream of cpp-tokens into
113    a text file.  */
114 static struct
115 {
116   FILE *outf;                   /* Stream to write to.  */
117   const cpp_token *prev;        /* Previous token.  */
118   const cpp_token *source;      /* Source token for spacing.  */
119   int src_line;                 /* Line number currently being written.  */
120   unsigned char printed;        /* Nonzero if something output at line.  */
121   bool first_time;              /* cb_file_change hasn't been called yet.  */
122 } print;
123
124 /* General output routines.  */
125 static void scan_translation_unit (cpp_reader *);
126 static void scan_translation_unit_trad (cpp_reader *);
127
128 /* Callback routines for the parser. Most of these are active only
129    in specific modes.  */
130 static void cb_file_change (cpp_reader *, const struct line_map *);
131 static void cb_line_change (cpp_reader *, const cpp_token *, int);
132 static void cb_define (cpp_reader *, source_location, cpp_hashnode *);
133 static void cb_undef (cpp_reader *, source_location, cpp_hashnode *);
134 static void cb_def_pragma (cpp_reader *, source_location);
135 static void cb_include (cpp_reader *, source_location, const unsigned char *,
136                         const char *, int, const cpp_token **);
137 static void cb_ident (cpp_reader *, source_location, const cpp_string *);
138 static void cb_used_define (cpp_reader *, source_location, cpp_hashnode *);
139 static void cb_used_undef (cpp_reader *, source_location, cpp_hashnode *);
140 static bool cb_cpp_error (cpp_reader *, int, int, location_t, unsigned int,
141                           const char *, va_list *)
142      ATTRIBUTE_GCC_DIAG(6,0);
143 void pp_dir_change (cpp_reader *, const char *);
144
145 static int dump_macro (cpp_reader *, cpp_hashnode *, void *);
146 static void dump_queued_macros (cpp_reader *);
147
148
149 static void
150 cpp_define_builtins (cpp_reader *pfile)
151 {
152   int major, minor, patchlevel;
153
154   /* Initialize CPP built-ins; '1' corresponds to 'flag_hosted'
155      in C, defines __STDC_HOSTED__?!  */
156   cpp_init_builtins (pfile, 0);
157
158   /* Initialize GFORTRAN specific builtins.
159      These are documented.  */
160   if (sscanf (BASEVER, "%d.%d.%d", &major, &minor, &patchlevel) != 3)
161     {
162       sscanf (BASEVER, "%d.%d", &major, &minor);
163       patchlevel = 0;
164     }
165   cpp_define_formatted (pfile, "__GNUC__=%d", major);
166   cpp_define_formatted (pfile, "__GNUC_MINOR__=%d", minor);
167   cpp_define_formatted (pfile, "__GNUC_PATCHLEVEL__=%d", patchlevel);
168
169   cpp_define (pfile, "__GFORTRAN__=1");
170   cpp_define (pfile, "_LANGUAGE_FORTRAN=1");
171
172   if (gfc_option.flag_openmp)
173     cpp_define (pfile, "_OPENMP=200805");
174
175
176   /* More builtins that might be useful, but are not documented
177      (in no particular order).  */
178   cpp_define_formatted (pfile, "__VERSION__=\"%s\"", version_string);
179
180   if (flag_pic)
181     {
182       cpp_define_formatted (pfile, "__pic__=%d", flag_pic);
183       cpp_define_formatted (pfile, "__PIC__=%d", flag_pic);
184     }
185   if (flag_pie)
186     {
187       cpp_define_formatted (pfile, "__pie__=%d", flag_pie);
188       cpp_define_formatted (pfile, "__PIE__=%d", flag_pie);
189     }
190
191   if (optimize_size)
192     cpp_define (pfile, "__OPTIMIZE_SIZE__");
193   if (optimize)
194     cpp_define (pfile, "__OPTIMIZE__");
195
196   if (fast_math_flags_set_p ())
197     cpp_define (pfile, "__FAST_MATH__");
198   if (flag_signaling_nans)
199     cpp_define (pfile, "__SUPPORT_SNAN__");
200
201   cpp_define_formatted (pfile, "__FINITE_MATH_ONLY__=%d", flag_finite_math_only);
202
203   /* Definitions for LP64 model. */
204   if (TYPE_PRECISION (long_integer_type_node) == 64
205       && POINTER_SIZE == 64
206       && TYPE_PRECISION (integer_type_node) == 32)
207     {
208       cpp_define (pfile, "_LP64");
209       cpp_define (pfile, "__LP64__");
210     }
211
212   /* Define NAME with value TYPE size_unit.
213      The C-side also defines __SIZEOF_WCHAR_T__, __SIZEOF_WINT_T__
214      __SIZEOF_PTRDIFF_T__, however, fortran seems to lack the
215      appropriate type nodes.  */
216
217 #define define_type_sizeof(NAME, TYPE)                             \
218     cpp_define_formatted (pfile, NAME"="HOST_WIDE_INT_PRINT_DEC,   \
219                           tree_low_cst (TYPE_SIZE_UNIT (TYPE), 1))
220
221   define_type_sizeof ("__SIZEOF_INT__", integer_type_node);
222   define_type_sizeof ("__SIZEOF_LONG__", long_integer_type_node);
223   define_type_sizeof ("__SIZEOF_LONG_LONG__", long_long_integer_type_node);
224   define_type_sizeof ("__SIZEOF_SHORT__", short_integer_type_node);
225   define_type_sizeof ("__SIZEOF_FLOAT__", float_type_node);
226   define_type_sizeof ("__SIZEOF_DOUBLE__", double_type_node);
227   define_type_sizeof ("__SIZEOF_LONG_DOUBLE__", long_double_type_node);
228   define_type_sizeof ("__SIZEOF_SIZE_T__", size_type_node);
229
230 #undef define_type_sizeof
231
232   /* The defines below are necessary for the TARGET_* macros.
233
234      FIXME:  Note that builtin_define_std() actually is a function
235      in c-cppbuiltin.c which uses flags undefined for Fortran.
236      Let's skip this for now. If needed, one needs to look into it
237      once more.  */
238
239 # define builtin_define(TXT) cpp_define (pfile, TXT)
240 # define builtin_define_std(TXT)
241 # define builtin_assert(TXT) cpp_assert (pfile, TXT)
242
243   /* FIXME: Pandora's Box
244     Using the macros below results in multiple breakages:
245      - mingw will fail to compile this file as dependent macros
246        assume to be used in c-cppbuiltin.c only. Further, they use
247        flags only valid/defined in C (same as noted above).
248        [config/i386/mingw32.h, config/i386/cygming.h]
249      - other platforms (not as popular) break similarly
250        [grep for 'builtin_define_with_int_value' in gcc/config/]
251
252   TARGET_CPU_CPP_BUILTINS ();
253   TARGET_OS_CPP_BUILTINS ();
254   TARGET_OBJFMT_CPP_BUILTINS (); */
255
256 #undef builtin_define
257 #undef builtin_define_std
258 #undef builtin_assert
259 }
260
261 bool
262 gfc_cpp_enabled (void)
263 {
264   return gfc_cpp_option.temporary_filename != NULL;
265 }
266
267 bool
268 gfc_cpp_preprocess_only (void)
269 {
270   return gfc_cpp_option.preprocess_only;
271 }
272
273 const char *
274 gfc_cpp_temporary_file (void)
275 {
276   return gfc_cpp_option.temporary_filename;
277 }
278
279 void
280 gfc_cpp_init_options (unsigned int argc,
281                       const char **argv ATTRIBUTE_UNUSED)
282 {
283   /* Do not create any objects from libcpp here. If no
284      preprocessing is requested, this would be wasted
285      time and effort.
286
287      See gfc_cpp_post_options() instead.  */
288
289   gfc_cpp_option.temporary_filename = NULL;
290   gfc_cpp_option.output_filename = NULL;
291   gfc_cpp_option.preprocess_only = 0;
292   gfc_cpp_option.discard_comments = 1;
293   gfc_cpp_option.discard_comments_in_macro_exp = 1;
294   gfc_cpp_option.print_include_names = 0;
295   gfc_cpp_option.no_line_commands = 0;
296   gfc_cpp_option.dump_macros = '\0';
297   gfc_cpp_option.dump_includes = 0;
298   gfc_cpp_option.working_directory = -1;
299   gfc_cpp_option.no_predefined = 0;
300   gfc_cpp_option.standard_include_paths = 1;
301   gfc_cpp_option.verbose = 0;
302
303   gfc_cpp_option.multilib = NULL;
304   gfc_cpp_option.prefix = NULL;
305   gfc_cpp_option.sysroot = NULL;
306
307   gfc_cpp_option.deferred_opt = XNEWVEC (gfc_cpp_deferred_opt_t, argc);
308   gfc_cpp_option.deferred_opt_count = 0;
309 }
310
311 int
312 gfc_cpp_handle_option (size_t scode, const char *arg, int value ATTRIBUTE_UNUSED)
313 {
314   int result = 1;
315   enum opt_code code = (enum opt_code) scode;
316
317   switch (code)
318   {
319     default:
320       result = 0;
321       break;
322
323     case OPT_cpp:
324       gfc_cpp_option.temporary_filename = arg;
325       break;
326
327     case OPT_nocpp:
328       gfc_cpp_option.temporary_filename = 0L;
329       break;
330
331     case OPT_d:
332       for ( ; *arg; ++arg)
333         switch (*arg)
334         {
335           case 'D':
336           case 'M':
337           case 'N':
338           case 'U':
339             gfc_cpp_option.dump_macros = *arg;
340             break;
341
342           case 'I':
343             gfc_cpp_option.dump_includes = 1;
344             break;
345         }
346       break;
347
348     case OPT_fworking_directory:
349       gfc_cpp_option.working_directory = value;
350       break;
351
352     case OPT_idirafter:
353       gfc_cpp_add_include_path_after (xstrdup(arg), true);
354       break;
355
356     case OPT_imultilib:
357       gfc_cpp_option.multilib = arg;
358       break;
359
360     case OPT_iprefix:
361       gfc_cpp_option.prefix = arg;
362       break;
363
364     case OPT_isysroot:
365       gfc_cpp_option.sysroot = arg;
366       break;
367
368     case OPT_iquote:
369     case OPT_isystem:
370       gfc_cpp_add_include_path (xstrdup(arg), true);
371       break;
372
373     case OPT_nostdinc:
374       gfc_cpp_option.standard_include_paths = value;
375       break;
376
377     case OPT_o:
378       if (!gfc_cpp_option.output_filename)
379         gfc_cpp_option.output_filename = arg;
380       else
381         gfc_fatal_error ("output filename specified twice");
382       break;
383
384     case OPT_undef:
385       gfc_cpp_option.no_predefined = value;
386       break;
387
388     case OPT_v:
389       gfc_cpp_option.verbose = value;
390       break;
391
392     case OPT_A:
393     case OPT_D:
394     case OPT_U:
395       gfc_cpp_option.deferred_opt[gfc_cpp_option.deferred_opt_count].code = code;
396       gfc_cpp_option.deferred_opt[gfc_cpp_option.deferred_opt_count].arg = arg;
397       gfc_cpp_option.deferred_opt_count++;
398       break;
399
400     case OPT_C:
401       gfc_cpp_option.discard_comments = 0;
402       break;
403
404     case OPT_CC:
405       gfc_cpp_option.discard_comments = 0;
406       gfc_cpp_option.discard_comments_in_macro_exp = 0;
407       break;
408
409     case OPT_E:
410       gfc_cpp_option.preprocess_only = 1;
411       break;
412
413     case OPT_H:
414       gfc_cpp_option.print_include_names = 1;
415       break;
416
417     case OPT_P:
418       gfc_cpp_option.no_line_commands = 1;
419       break;
420   }
421
422   return result;
423 }
424
425
426 void
427 gfc_cpp_post_options (void)
428 {
429   /* Any preprocessing-related option without '-cpp' is considered
430      an error.  */
431   if (!gfc_cpp_enabled ()
432       && (gfc_cpp_preprocess_only ()
433           || !gfc_cpp_option.discard_comments
434           || !gfc_cpp_option.discard_comments_in_macro_exp
435           || gfc_cpp_option.print_include_names
436           || gfc_cpp_option.no_line_commands
437           || gfc_cpp_option.dump_macros
438           || gfc_cpp_option.dump_includes))
439     gfc_fatal_error("To enable preprocessing, use -cpp");
440
441   cpp_in = cpp_create_reader (CLK_GNUC89, NULL, line_table);
442   if (!gfc_cpp_enabled())
443     return;
444
445   gcc_assert (cpp_in);
446
447   /* The cpp_options-structure defines far more flags than those set here.
448      If any other is implemented, see c-opt.c (sanitize_cpp_opts) for
449      inter-option dependencies that may need to be enforced.  */
450   cpp_option = cpp_get_options (cpp_in);
451   gcc_assert (cpp_option);
452
453   /* TODO: allow non-traditional modes, e.g. by -cpp-std=...?  */
454   cpp_option->traditional = 1;
455   cpp_option->cplusplus_comments = 0;
456
457   cpp_option->pedantic = pedantic;
458
459   cpp_option->dollars_in_ident = gfc_option.flag_dollar_ok;
460   cpp_option->discard_comments = gfc_cpp_option.discard_comments;
461   cpp_option->discard_comments_in_macro_exp = gfc_cpp_option.discard_comments_in_macro_exp;
462   cpp_option->print_include_names = gfc_cpp_option.print_include_names;
463   cpp_option->preprocessed = gfc_option.flag_preprocessed;
464
465   if (gfc_cpp_option.working_directory == -1)
466     gfc_cpp_option.working_directory = (debug_info_level != DINFO_LEVEL_NONE);
467
468   cpp_post_options (cpp_in);
469
470   gfc_cpp_register_include_paths ();
471 }
472
473
474 void
475 gfc_cpp_init_0 (void)
476 {
477   struct cpp_callbacks *cb;
478
479   cb = cpp_get_callbacks (cpp_in);
480   cb->file_change = cb_file_change;
481   cb->line_change = cb_line_change;
482   cb->ident = cb_ident;
483   cb->def_pragma = cb_def_pragma;
484   cb->error = cb_cpp_error;
485
486   if (gfc_cpp_option.dump_includes)
487     cb->include = cb_include;
488
489   if ((gfc_cpp_option.dump_macros == 'D')
490       || (gfc_cpp_option.dump_macros == 'N'))
491     {
492       cb->define = cb_define;
493       cb->undef  = cb_undef;
494     }
495
496   if (gfc_cpp_option.dump_macros == 'U')
497     {
498       cb->before_define = dump_queued_macros;
499       cb->used_define = cb_used_define;
500       cb->used_undef = cb_used_undef;
501     }
502
503   /* Initialize the print structure.  Setting print.src_line to -1 here is
504      a trick to guarantee that the first token of the file will cause
505      a linemarker to be output by maybe_print_line.  */
506   print.src_line = -1;
507   print.printed = 0;
508   print.prev = 0;
509   print.first_time = 1;
510
511   if (gfc_cpp_preprocess_only ())
512     {
513       if (gfc_cpp_option.output_filename)
514         {
515           /* This needs cheating: with "-E -o <file>", the user wants the
516              preprocessed output in <file>. However, if nothing is done
517              about it <file> is also used for assembler output. Hence, it
518              is necessary to redirect assembler output (actually nothing
519              as -E implies -fsyntax-only) to another file, otherwise the
520              output from preprocessing is lost.  */
521           asm_file_name = gfc_cpp_option.temporary_filename;
522
523           print.outf = fopen (gfc_cpp_option.output_filename, "w");
524           if (print.outf == NULL)
525             gfc_fatal_error ("opening output file %s: %s",
526                              gfc_cpp_option.output_filename,
527                              xstrerror (errno));
528         }
529       else
530         print.outf = stdout;
531     }
532   else
533     {
534       print.outf = fopen (gfc_cpp_option.temporary_filename, "w");
535       if (print.outf == NULL)
536         gfc_fatal_error ("opening output file %s: %s",
537                          gfc_cpp_option.temporary_filename, xstrerror (errno));
538     }
539
540   gcc_assert(cpp_in);
541   if (!cpp_read_main_file (cpp_in, gfc_source_file))
542     errorcount++;
543 }
544
545 void
546 gfc_cpp_init (void)
547 {
548   int i;
549
550   if (gfc_option.flag_preprocessed)
551     return;
552
553   cpp_change_file (cpp_in, LC_RENAME, _("<built-in>"));
554   if (!gfc_cpp_option.no_predefined)
555     cpp_define_builtins (cpp_in);
556
557   /* Handle deferred options from command-line.  */
558   cpp_change_file (cpp_in, LC_RENAME, _("<command-line>"));
559
560   for (i = 0; i < gfc_cpp_option.deferred_opt_count; i++)
561     {
562       gfc_cpp_deferred_opt_t *opt = &gfc_cpp_option.deferred_opt[i];
563
564       if (opt->code == OPT_D)
565         cpp_define (cpp_in, opt->arg);
566       else if (opt->code == OPT_U)
567         cpp_undef (cpp_in, opt->arg);
568       else if (opt->code == OPT_A)
569         {
570           if (opt->arg[0] == '-')
571             cpp_unassert (cpp_in, opt->arg + 1);
572           else
573             cpp_assert (cpp_in, opt->arg);
574         }
575     }
576
577   if (gfc_cpp_option.working_directory
578       && gfc_cpp_option.preprocess_only && !gfc_cpp_option.no_line_commands)
579     pp_dir_change (cpp_in, get_src_pwd ());
580 }
581
582 gfc_try
583 gfc_cpp_preprocess (const char *source_file)
584 {
585   if (!gfc_cpp_enabled ())
586     return FAILURE;
587
588   cpp_change_file (cpp_in, LC_RENAME, source_file);
589
590   if (cpp_option->traditional)
591     scan_translation_unit_trad (cpp_in);
592   else
593     scan_translation_unit (cpp_in);
594
595   /* -dM command line option.  */
596   if (gfc_cpp_preprocess_only () &&
597       gfc_cpp_option.dump_macros == 'M')
598     {
599       putc ('\n', print.outf);
600       cpp_forall_identifiers (cpp_in, dump_macro, NULL);
601     }
602
603   putc ('\n', print.outf);
604
605   if (!gfc_cpp_preprocess_only ()
606       || (gfc_cpp_preprocess_only () && gfc_cpp_option.output_filename))
607     fclose (print.outf);
608
609   return SUCCESS;
610 }
611
612 void
613 gfc_cpp_done (void)
614 {
615   if (!gfc_cpp_enabled ())
616     return;
617
618   /* TODO: if dependency tracking was enabled, call
619      cpp_finish() here to write dependencies.
620
621      Use cpp_get_deps() to access the current source's
622      dependencies during parsing. Add dependencies using
623      the mkdeps-interface (defined in libcpp).  */
624
625   gcc_assert (cpp_in);
626   cpp_undef_all (cpp_in);
627   cpp_clear_file_cache (cpp_in);
628 }
629
630 /* PATH must be malloc-ed and NULL-terminated.  */
631 void
632 gfc_cpp_add_include_path (char *path, bool user_supplied)
633 {
634   /* CHAIN sets cpp_dir->sysp which differs from 0 if PATH is a system
635      include path. Fortran does not define any system include paths.  */
636   int cxx_aware = 0;
637
638   add_path (path, BRACKET, cxx_aware, user_supplied);
639 }
640
641 void
642 gfc_cpp_add_include_path_after (char *path, bool user_supplied)
643 {
644   int cxx_aware = 0;
645   add_path (path, AFTER, cxx_aware, user_supplied);
646 }
647
648 void
649 gfc_cpp_register_include_paths (void)
650 {
651   int cxx_stdinc = 0;
652   register_include_chains (cpp_in, gfc_cpp_option.sysroot,
653                            gfc_cpp_option.prefix, gfc_cpp_option.multilib,
654                            gfc_cpp_option.standard_include_paths, cxx_stdinc,
655                            gfc_cpp_option.verbose);
656 }
657
658
659
660 static void scan_translation_unit_trad (cpp_reader *);
661 static void account_for_newlines (const unsigned char *, size_t);
662 static int dump_macro (cpp_reader *, cpp_hashnode *, void *);
663
664 static void print_line (source_location, const char *);
665 static void maybe_print_line (source_location);
666
667
668 /* Writes out the preprocessed file, handling spacing and paste
669    avoidance issues.  */
670 static void
671 scan_translation_unit (cpp_reader *pfile)
672 {
673   bool avoid_paste = false;
674
675   print.source = NULL;
676   for (;;)
677     {
678       const cpp_token *token = cpp_get_token (pfile);
679
680       if (token->type == CPP_PADDING)
681         {
682           avoid_paste = true;
683           if (print.source == NULL
684               || (!(print.source->flags & PREV_WHITE)
685                   && token->val.source == NULL))
686             print.source = token->val.source;
687           continue;
688         }
689
690       if (token->type == CPP_EOF)
691         break;
692
693       /* Subtle logic to output a space if and only if necessary.  */
694       if (avoid_paste)
695         {
696           if (print.source == NULL)
697             print.source = token;
698           if (print.source->flags & PREV_WHITE
699               || (print.prev
700                   && cpp_avoid_paste (pfile, print.prev, token))
701               || (print.prev == NULL && token->type == CPP_HASH))
702             putc (' ', print.outf);
703         }
704       else if (token->flags & PREV_WHITE)
705         putc (' ', print.outf);
706
707       avoid_paste = false;
708       print.source = NULL;
709       print.prev = token;
710       cpp_output_token (token, print.outf);
711
712       if (token->type == CPP_COMMENT)
713         account_for_newlines (token->val.str.text, token->val.str.len);
714     }
715 }
716
717 /* Adjust print.src_line for newlines embedded in output.  */
718 static void
719 account_for_newlines (const unsigned char *str, size_t len)
720 {
721   while (len--)
722     if (*str++ == '\n')
723       print.src_line++;
724 }
725
726 /* Writes out a traditionally preprocessed file.  */
727 static void
728 scan_translation_unit_trad (cpp_reader *pfile)
729 {
730   while (_cpp_read_logical_line_trad (pfile))
731     {
732       size_t len = pfile->out.cur - pfile->out.base;
733       maybe_print_line (pfile->out.first_line);
734       fwrite (pfile->out.base, 1, len, print.outf);
735       print.printed = 1;
736       if (!CPP_OPTION (pfile, discard_comments))
737         account_for_newlines (pfile->out.base, len);
738     }
739 }
740
741 /* If the token read on logical line LINE needs to be output on a
742    different line to the current one, output the required newlines or
743    a line marker.  */
744 static void
745 maybe_print_line (source_location src_loc)
746 {
747   const struct line_map *map = linemap_lookup (line_table, src_loc);
748   int src_line = SOURCE_LINE (map, src_loc);
749
750   /* End the previous line of text.  */
751   if (print.printed)
752     {
753       putc ('\n', print.outf);
754       print.src_line++;
755       print.printed = 0;
756     }
757
758   if (src_line >= print.src_line && src_line < print.src_line + 8)
759     {
760       while (src_line > print.src_line)
761         {
762           putc ('\n', print.outf);
763           print.src_line++;
764         }
765     }
766   else
767     print_line (src_loc, "");
768 }
769
770 /* Output a line marker for logical line LINE.  Special flags are "1"
771    or "2" indicating entering or leaving a file.  */
772 static void
773 print_line (source_location src_loc, const char *special_flags)
774 {
775   /* End any previous line of text.  */
776   if (print.printed)
777     putc ('\n', print.outf);
778   print.printed = 0;
779
780   if (!gfc_cpp_option.no_line_commands)
781     {
782       const struct line_map *map = linemap_lookup (line_table, src_loc);
783
784       size_t to_file_len = strlen (map->to_file);
785       unsigned char *to_file_quoted =
786          (unsigned char *) alloca (to_file_len * 4 + 1);
787       unsigned char *p;
788
789       print.src_line = SOURCE_LINE (map, src_loc);
790
791       /* cpp_quote_string does not nul-terminate, so we have to do it
792          ourselves.  */
793       p = cpp_quote_string (to_file_quoted,
794                             (const unsigned char *) map->to_file, to_file_len);
795       *p = '\0';
796       fprintf (print.outf, "# %u \"%s\"%s",
797                print.src_line == 0 ? 1 : print.src_line,
798                to_file_quoted, special_flags);
799
800       if (map->sysp == 2)
801         fputs (" 3 4", print.outf);
802       else if (map->sysp == 1)
803         fputs (" 3", print.outf);
804
805       putc ('\n', print.outf);
806     }
807 }
808
809 static void
810 cb_file_change (cpp_reader * ARG_UNUSED (pfile), const struct line_map *map)
811 {
812   const char *flags = "";
813
814   if (gfc_cpp_option.no_line_commands)
815     return;
816
817   if (!map)
818     return;
819
820       if (print.first_time)
821         {
822           /* Avoid printing foo.i when the main file is foo.c.  */
823           if (!cpp_get_options (cpp_in)->preprocessed)
824             print_line (map->start_location, flags);
825           print.first_time = 0;
826         }
827       else
828         {
829           /* Bring current file to correct line when entering a new file.  */
830           if (map->reason == LC_ENTER)
831             {
832               const struct line_map *from = INCLUDED_FROM (line_table, map);
833               maybe_print_line (LAST_SOURCE_LINE_LOCATION (from));
834             }
835           if (map->reason == LC_ENTER)
836             flags = " 1";
837           else if (map->reason == LC_LEAVE)
838             flags = " 2";
839           print_line (map->start_location, flags);
840         }
841
842 }
843
844 /* Called when a line of output is started.  TOKEN is the first token
845    of the line, and at end of file will be CPP_EOF.  */
846 static void
847 cb_line_change (cpp_reader *pfile, const cpp_token *token,
848                 int parsing_args)
849 {
850   source_location src_loc = token->src_loc;
851
852   if (token->type == CPP_EOF || parsing_args)
853     return;
854
855   maybe_print_line (src_loc);
856   print.prev = 0;
857   print.source = 0;
858
859   /* Supply enough spaces to put this token in its original column,
860      one space per column greater than 2, since scan_translation_unit
861      will provide a space if PREV_WHITE.  Don't bother trying to
862      reconstruct tabs; we can't get it right in general, and nothing
863      ought to care.  Some things do care; the fault lies with them.  */
864   if (!CPP_OPTION (pfile, traditional))
865     {
866       const struct line_map *map = linemap_lookup (line_table, src_loc);
867       int spaces = SOURCE_COLUMN (map, src_loc) - 2;
868       print.printed = 1;
869
870       while (-- spaces >= 0)
871         putc (' ', print.outf);
872     }
873 }
874
875 static void
876 cb_ident (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
877           const cpp_string *str)
878 {
879   maybe_print_line (line);
880   fprintf (print.outf, "#ident %s\n", str->text);
881   print.src_line++;
882 }
883
884 static void
885 cb_define (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
886            cpp_hashnode *node ATTRIBUTE_UNUSED)
887 {
888   maybe_print_line (line);
889   fputs ("#define ", print.outf);
890
891   /* 'D' is whole definition; 'N' is name only.  */
892   if (gfc_cpp_option.dump_macros == 'D')
893     fputs ((const char *) cpp_macro_definition (pfile, node),
894            print.outf);
895   else
896     fputs ((const char *) NODE_NAME (node), print.outf);
897
898   putc ('\n', print.outf);
899   if (linemap_lookup (line_table, line)->to_line != 0)
900     print.src_line++;
901 }
902
903 static void
904 cb_undef (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
905           cpp_hashnode *node)
906 {
907   maybe_print_line (line);
908   fprintf (print.outf, "#undef %s\n", NODE_NAME (node));
909   print.src_line++;
910 }
911
912 static void
913 cb_include (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
914             const unsigned char *dir, const char *header, int angle_brackets,
915             const cpp_token **comments)
916 {
917   maybe_print_line (line);
918   if (angle_brackets)
919     fprintf (print.outf, "#%s <%s>", dir, header);
920   else
921     fprintf (print.outf, "#%s \"%s\"", dir, header);
922
923   if (comments != NULL)
924     {
925       while (*comments != NULL)
926         {
927           if ((*comments)->flags & PREV_WHITE)
928             putc (' ', print.outf);
929           cpp_output_token (*comments, print.outf);
930           ++comments;
931         }
932     }
933
934   putc ('\n', print.outf);
935   print.src_line++;
936 }
937
938 /* Dump out the hash table.  */
939 static int
940 dump_macro (cpp_reader *pfile, cpp_hashnode *node, void *v ATTRIBUTE_UNUSED)
941 {
942   if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
943     {
944       fputs ("#define ", print.outf);
945       fputs ((const char *) cpp_macro_definition (pfile, node),
946              print.outf);
947       putc ('\n', print.outf);
948       print.src_line++;
949     }
950
951   return 1;
952 }
953
954 static void
955 cb_used_define (cpp_reader *pfile, source_location line ATTRIBUTE_UNUSED,
956                 cpp_hashnode *node)
957 {
958   gfc_cpp_macro_queue *q;
959   q = XNEW (gfc_cpp_macro_queue);
960   q->macro = xstrdup ((const char *) cpp_macro_definition (pfile, node));
961   q->next = cpp_define_queue;
962   cpp_define_queue = q;
963 }
964
965 /* Callback from cpp_error for PFILE to print diagnostics from the
966    preprocessor.  The diagnostic is of type LEVEL, with REASON set
967    to the reason code if LEVEL is represents a warning, at location
968    LOCATION, with column number possibly overridden by COLUMN_OVERRIDE
969    if not zero; MSG is the translated message and AP the arguments.
970    Returns true if a diagnostic was emitted, false otherwise.  */
971
972 static bool
973 cb_cpp_error (cpp_reader *pfile ATTRIBUTE_UNUSED, int level, int reason,
974               location_t location, unsigned int column_override,
975               const char *msg, va_list *ap)
976 {
977   diagnostic_info diagnostic;
978   diagnostic_t dlevel;
979   bool save_warn_system_headers = global_dc->warn_system_headers;
980   bool ret;
981
982   switch (level)
983     {
984     case CPP_DL_WARNING_SYSHDR:
985       global_dc->warn_system_headers = 1;
986       /* Fall through.  */
987     case CPP_DL_WARNING:
988       dlevel = DK_WARNING;
989       break;
990     case CPP_DL_PEDWARN:
991       dlevel = DK_PEDWARN;
992       break;
993     case CPP_DL_ERROR:
994       dlevel = DK_ERROR;
995       break;
996     case CPP_DL_ICE:
997       dlevel = DK_ICE;
998       break;
999     case CPP_DL_NOTE:
1000       dlevel = DK_NOTE;
1001       break;
1002     case CPP_DL_FATAL:
1003       dlevel = DK_FATAL;
1004       break;
1005     default:
1006       gcc_unreachable ();
1007     }
1008   diagnostic_set_info_translated (&diagnostic, msg, ap,
1009                                   location, dlevel);
1010   if (column_override)
1011     diagnostic_override_column (&diagnostic, column_override);
1012   if (reason == CPP_W_WARNING_DIRECTIVE)
1013     diagnostic_override_option_index (&diagnostic, OPT_Wcpp);
1014   ret = report_diagnostic (&diagnostic);
1015   if (level == CPP_DL_WARNING_SYSHDR)
1016     global_dc->warn_system_headers = save_warn_system_headers;
1017   return ret;
1018 }
1019
1020 /* Callback called when -fworking-director and -E to emit working
1021    directory in cpp output file.  */
1022
1023 void
1024 pp_dir_change (cpp_reader *pfile ATTRIBUTE_UNUSED, const char *dir)
1025 {
1026   size_t to_file_len = strlen (dir);
1027   unsigned char *to_file_quoted =
1028      (unsigned char *) alloca (to_file_len * 4 + 1);
1029   unsigned char *p;
1030
1031   /* cpp_quote_string does not nul-terminate, so we have to do it ourselves.  */
1032   p = cpp_quote_string (to_file_quoted, (const unsigned char *) dir, to_file_len);
1033   *p = '\0';
1034   fprintf (print.outf, "# 1 \"%s//\"\n", to_file_quoted);
1035 }
1036
1037 /* Copy a #pragma directive to the preprocessed output.  */
1038 static void
1039 cb_def_pragma (cpp_reader *pfile, source_location line)
1040 {
1041   maybe_print_line (line);
1042   fputs ("#pragma ", print.outf);
1043   cpp_output_line (pfile, print.outf);
1044   print.src_line++;
1045 }
1046
1047 static void
1048 cb_used_undef (cpp_reader *pfile ATTRIBUTE_UNUSED,
1049                source_location line ATTRIBUTE_UNUSED,
1050                cpp_hashnode *node)
1051 {
1052   gfc_cpp_macro_queue *q;
1053   q = XNEW (gfc_cpp_macro_queue);
1054   q->macro = xstrdup ((const char *) NODE_NAME (node));
1055   q->next = cpp_undefine_queue;
1056   cpp_undefine_queue = q;
1057 }
1058
1059 static void
1060 dump_queued_macros (cpp_reader *pfile ATTRIBUTE_UNUSED)
1061 {
1062   gfc_cpp_macro_queue *q;
1063
1064   /* End the previous line of text.  */
1065   if (print.printed)
1066     {
1067       putc ('\n', print.outf);
1068       print.src_line++;
1069       print.printed = 0;
1070     }
1071
1072   for (q = cpp_define_queue; q;)
1073     {
1074       gfc_cpp_macro_queue *oq;
1075       fputs ("#define ", print.outf);
1076       fputs (q->macro, print.outf);
1077       putc ('\n', print.outf);
1078       print.src_line++;
1079       oq = q;
1080       q = q->next;
1081       gfc_free (oq->macro);
1082       gfc_free (oq);
1083     }
1084   cpp_define_queue = NULL;
1085   for (q = cpp_undefine_queue; q;)
1086     {
1087       gfc_cpp_macro_queue *oq;
1088       fprintf (print.outf, "#undef %s\n", q->macro);
1089       print.src_line++;
1090       oq = q;
1091       q = q->next;
1092       gfc_free (oq->macro);
1093       gfc_free (oq);
1094     }
1095   cpp_undefine_queue = NULL;
1096 }