OSDN Git Service

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