1/* Preprocess only, using cpplib.
2   Copyright (C) 1995, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
3   Free Software Foundation, Inc.
4   Written by Per Bothner, 1994-95.
5
6This program is free software; you can redistribute it and/or modify it
7under the terms of the GNU General Public License as published by the
8Free Software Foundation; either version 2, or (at your option) any
9later version.
10
11This program is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with this program; if not, write to the Free Software
18Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20#include "config.h"
21#include "system.h"
22#include "coretypes.h"
23#include "tm.h"
24#include "cpplib.h"
25#include "../libcpp/internal.h"
26#include "tree.h"
27#include "c-common.h"		/* For flags.  */
28#include "c-pragma.h"		/* For parse_in.  */
29
30/* Encapsulates state used to convert a stream of tokens into a text
31   file.  */
32static struct
33{
34  FILE *outf;			/* Stream to write to.  */
35  const cpp_token *prev;	/* Previous token.  */
36  const cpp_token *source;	/* Source token for spacing.  */
37  int src_line;			/* Line number currently being written.  */
38  unsigned char printed;	/* Nonzero if something output at line.  */
39  bool first_time;		/* pp_file_change hasn't been called yet.  */
40} print;
41
42/* General output routines.  */
43static void scan_translation_unit (cpp_reader *);
44static void scan_translation_unit_trad (cpp_reader *);
45static void account_for_newlines (const unsigned char *, size_t);
46static int dump_macro (cpp_reader *, cpp_hashnode *, void *);
47
48static void print_line (source_location, const char *);
49static void maybe_print_line (source_location);
50
51/* Callback routines for the parser.   Most of these are active only
52   in specific modes.  */
53static void cb_line_change (cpp_reader *, const cpp_token *, int);
54static void cb_define (cpp_reader *, source_location, cpp_hashnode *);
55static void cb_undef (cpp_reader *, source_location, cpp_hashnode *);
56static void cb_include (cpp_reader *, source_location, const unsigned char *,
57			const char *, int, const cpp_token **);
58static void cb_ident (cpp_reader *, source_location, const cpp_string *);
59static void cb_def_pragma (cpp_reader *, source_location);
60static void cb_read_pch (cpp_reader *pfile, const char *name,
61			 int fd, const char *orig_name);
62
63/* Preprocess and output.  */
64void
65preprocess_file (cpp_reader *pfile)
66{
67  /* A successful cpp_read_main_file guarantees that we can call
68     cpp_scan_nooutput or cpp_get_token next.  */
69  if (flag_no_output)
70    {
71      /* Scan -included buffers, then the main file.  */
72      while (pfile->buffer->prev)
73	cpp_scan_nooutput (pfile);
74      cpp_scan_nooutput (pfile);
75    }
76  else if (cpp_get_options (pfile)->traditional)
77    scan_translation_unit_trad (pfile);
78  else
79    scan_translation_unit (pfile);
80
81  /* -dM command line option.  Should this be elsewhere?  */
82  if (flag_dump_macros == 'M')
83    cpp_forall_identifiers (pfile, dump_macro, NULL);
84
85  /* Flush any pending output.  */
86  if (print.printed)
87    putc ('\n', print.outf);
88}
89
90/* Set up the callbacks as appropriate.  */
91void
92init_pp_output (FILE *out_stream)
93{
94  cpp_callbacks *cb = cpp_get_callbacks (parse_in);
95
96  if (!flag_no_output)
97    {
98      cb->line_change = cb_line_change;
99      /* Don't emit #pragma or #ident directives if we are processing
100	 assembly language; the assembler may choke on them.  */
101      if (cpp_get_options (parse_in)->lang != CLK_ASM)
102	{
103	  cb->ident      = cb_ident;
104	  cb->def_pragma = cb_def_pragma;
105	}
106    }
107
108  if (flag_dump_includes)
109    cb->include  = cb_include;
110
111  if (flag_pch_preprocess)
112    {
113      cb->valid_pch = c_common_valid_pch;
114      cb->read_pch = cb_read_pch;
115    }
116
117  if (flag_dump_macros == 'N' || flag_dump_macros == 'D')
118    {
119      cb->define = cb_define;
120      cb->undef  = cb_undef;
121    }
122
123  /* Initialize the print structure.  Setting print.src_line to -1 here is
124     a trick to guarantee that the first token of the file will cause
125     a linemarker to be output by maybe_print_line.  */
126  print.src_line = -1;
127  print.printed = 0;
128  print.prev = 0;
129  print.outf = out_stream;
130  print.first_time = 1;
131}
132
133/* Writes out the preprocessed file, handling spacing and paste
134   avoidance issues.  */
135static void
136scan_translation_unit (cpp_reader *pfile)
137{
138  bool avoid_paste = false;
139
140  print.source = NULL;
141  for (;;)
142    {
143      const cpp_token *token = cpp_get_token (pfile);
144
145      if (token->type == CPP_PADDING)
146	{
147	  avoid_paste = true;
148	  if (print.source == NULL
149	      || (!(print.source->flags & PREV_WHITE)
150		  && token->val.source == NULL))
151	    print.source = token->val.source;
152	  continue;
153	}
154
155      if (token->type == CPP_EOF)
156	break;
157
158      /* Subtle logic to output a space if and only if necessary.  */
159      if (avoid_paste)
160	{
161	  if (print.source == NULL)
162	    print.source = token;
163	  if (print.source->flags & PREV_WHITE
164	      || (print.prev
165		  && cpp_avoid_paste (pfile, print.prev, token))
166	      || (print.prev == NULL && token->type == CPP_HASH))
167	    putc (' ', print.outf);
168	}
169      else if (token->flags & PREV_WHITE)
170	putc (' ', print.outf);
171
172      avoid_paste = false;
173      print.source = NULL;
174      print.prev = token;
175      cpp_output_token (token, print.outf);
176
177      if (token->type == CPP_COMMENT)
178	account_for_newlines (token->val.str.text, token->val.str.len);
179    }
180}
181
182/* Adjust print.src_line for newlines embedded in output.  */
183static void
184account_for_newlines (const unsigned char *str, size_t len)
185{
186  while (len--)
187    if (*str++ == '\n')
188      print.src_line++;
189}
190
191/* Writes out a traditionally preprocessed file.  */
192static void
193scan_translation_unit_trad (cpp_reader *pfile)
194{
195  while (_cpp_read_logical_line_trad (pfile))
196    {
197      size_t len = pfile->out.cur - pfile->out.base;
198      maybe_print_line (pfile->out.first_line);
199      fwrite (pfile->out.base, 1, len, print.outf);
200      print.printed = 1;
201      if (!CPP_OPTION (pfile, discard_comments))
202	account_for_newlines (pfile->out.base, len);
203    }
204}
205
206/* If the token read on logical line LINE needs to be output on a
207   different line to the current one, output the required newlines or
208   a line marker, and return 1.  Otherwise return 0.  */
209static void
210maybe_print_line (source_location src_loc)
211{
212  const struct line_map *map = linemap_lookup (&line_table, src_loc);
213  int src_line = SOURCE_LINE (map, src_loc);
214  /* End the previous line of text.  */
215  if (print.printed)
216    {
217      putc ('\n', print.outf);
218      print.src_line++;
219      print.printed = 0;
220    }
221
222  if (src_line >= print.src_line && src_line < print.src_line + 8)
223    {
224      while (src_line > print.src_line)
225	{
226	  putc ('\n', print.outf);
227	  print.src_line++;
228	}
229    }
230  else
231    print_line (src_loc, "");
232}
233
234/* Output a line marker for logical line LINE.  Special flags are "1"
235   or "2" indicating entering or leaving a file.  */
236static void
237print_line (source_location src_loc, const char *special_flags)
238{
239  /* End any previous line of text.  */
240  if (print.printed)
241    putc ('\n', print.outf);
242  print.printed = 0;
243
244  if (!flag_no_line_commands)
245    {
246      const struct line_map *map = linemap_lookup (&line_table, src_loc);
247
248      size_t to_file_len = strlen (map->to_file);
249      unsigned char *to_file_quoted = alloca (to_file_len * 4 + 1);
250      unsigned char *p;
251
252      print.src_line = SOURCE_LINE (map, src_loc);
253
254      /* cpp_quote_string does not nul-terminate, so we have to do it
255	 ourselves.  */
256      p = cpp_quote_string (to_file_quoted,
257			    (unsigned char *) map->to_file, to_file_len);
258      *p = '\0';
259      fprintf (print.outf, "# %u \"%s\"%s",
260	       print.src_line == 0 ? 1 : print.src_line,
261	       to_file_quoted, special_flags);
262
263      if (map->sysp == 2)
264	fputs (" 3 4", print.outf);
265      else if (map->sysp == 1)
266	fputs (" 3", print.outf);
267
268      putc ('\n', print.outf);
269    }
270}
271
272/* Called when a line of output is started.  TOKEN is the first token
273   of the line, and at end of file will be CPP_EOF.  */
274static void
275cb_line_change (cpp_reader *pfile, const cpp_token *token,
276		int parsing_args)
277{
278  source_location src_loc = token->src_loc;
279
280  if (token->type == CPP_EOF || parsing_args)
281    return;
282
283  maybe_print_line (src_loc);
284  print.prev = 0;
285  print.source = 0;
286
287  /* Supply enough spaces to put this token in its original column,
288     one space per column greater than 2, since scan_translation_unit
289     will provide a space if PREV_WHITE.  Don't bother trying to
290     reconstruct tabs; we can't get it right in general, and nothing
291     ought to care.  Some things do care; the fault lies with them.  */
292  if (!CPP_OPTION (pfile, traditional))
293    {
294      const struct line_map *map = linemap_lookup (&line_table, src_loc);
295      int spaces = SOURCE_COLUMN (map, src_loc) - 2;
296      print.printed = 1;
297
298      while (-- spaces >= 0)
299	putc (' ', print.outf);
300    }
301}
302
303static void
304cb_ident (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
305	  const cpp_string *str)
306{
307  maybe_print_line (line);
308  fprintf (print.outf, "#ident %s\n", str->text);
309  print.src_line++;
310}
311
312static void
313cb_define (cpp_reader *pfile, source_location line, cpp_hashnode *node)
314{
315  maybe_print_line (line);
316  fputs ("#define ", print.outf);
317
318  /* 'D' is whole definition; 'N' is name only.  */
319  if (flag_dump_macros == 'D')
320    fputs ((const char *) cpp_macro_definition (pfile, node),
321	   print.outf);
322  else
323    fputs ((const char *) NODE_NAME (node), print.outf);
324
325  putc ('\n', print.outf);
326  print.src_line++;
327}
328
329static void
330cb_undef (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
331	  cpp_hashnode *node)
332{
333  maybe_print_line (line);
334  fprintf (print.outf, "#undef %s\n", NODE_NAME (node));
335  print.src_line++;
336}
337
338static void
339cb_include (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
340	    const unsigned char *dir, const char *header, int angle_brackets,
341	    const cpp_token **comments)
342{
343  maybe_print_line (line);
344  if (angle_brackets)
345    fprintf (print.outf, "#%s <%s>", dir, header);
346  else
347    fprintf (print.outf, "#%s \"%s\"", dir, header);
348
349  if (comments != NULL)
350    {
351      while (*comments != NULL)
352	{
353	  if ((*comments)->flags & PREV_WHITE)
354	    putc (' ', print.outf);
355	  cpp_output_token (*comments, print.outf);
356	  ++comments;
357	}
358    }
359
360  putc ('\n', print.outf);
361  print.src_line++;
362}
363
364/* Callback called when -fworking-director and -E to emit working
365   directory in cpp output file.  */
366
367void
368pp_dir_change (cpp_reader *pfile ATTRIBUTE_UNUSED, const char *dir)
369{
370  size_t to_file_len = strlen (dir);
371  unsigned char *to_file_quoted = alloca (to_file_len * 4 + 1);
372  unsigned char *p;
373
374  /* cpp_quote_string does not nul-terminate, so we have to do it ourselves.  */
375  p = cpp_quote_string (to_file_quoted, (unsigned char *) dir, to_file_len);
376  *p = '\0';
377  fprintf (print.outf, "# 1 \"%s//\"\n", to_file_quoted);
378}
379
380/* The file name, line number or system header flags have changed, as
381   described in MAP.  */
382
383void
384pp_file_change (const struct line_map *map)
385{
386  const char *flags = "";
387
388  if (flag_no_line_commands)
389    return;
390
391  if (map != NULL)
392    {
393      if (print.first_time)
394	{
395	  /* Avoid printing foo.i when the main file is foo.c.  */
396	  if (!cpp_get_options (parse_in)->preprocessed)
397	    print_line (map->start_location, flags);
398	  print.first_time = 0;
399	}
400      else
401	{
402	  /* Bring current file to correct line when entering a new file.  */
403	  if (map->reason == LC_ENTER)
404	    {
405	      const struct line_map *from = INCLUDED_FROM (&line_table, map);
406	      maybe_print_line (LAST_SOURCE_LINE_LOCATION (from));
407	    }
408	  if (map->reason == LC_ENTER)
409	    flags = " 1";
410	  else if (map->reason == LC_LEAVE)
411	    flags = " 2";
412	  print_line (map->start_location, flags);
413	}
414    }
415}
416
417/* Copy a #pragma directive to the preprocessed output.  */
418static void
419cb_def_pragma (cpp_reader *pfile, source_location line)
420{
421  maybe_print_line (line);
422  fputs ("#pragma ", print.outf);
423  cpp_output_line (pfile, print.outf);
424  print.src_line++;
425}
426
427/* Dump out the hash table.  */
428static int
429dump_macro (cpp_reader *pfile, cpp_hashnode *node, void *v ATTRIBUTE_UNUSED)
430{
431  if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
432    {
433      fputs ("#define ", print.outf);
434      fputs ((const char *) cpp_macro_definition (pfile, node),
435	     print.outf);
436      putc ('\n', print.outf);
437      print.src_line++;
438    }
439
440  return 1;
441}
442
443/* Load in the PCH file NAME, open on FD.  It was originally searched for
444   by ORIG_NAME.  Also, print out a #include command so that the PCH
445   file can be loaded when the preprocessed output is compiled.  */
446
447static void
448cb_read_pch (cpp_reader *pfile, const char *name,
449	     int fd, const char *orig_name ATTRIBUTE_UNUSED)
450{
451  c_common_read_pch (pfile, name, fd, orig_name);
452
453  fprintf (print.outf, "#pragma GCC pch_preprocess \"%s\"\n", name);
454  print.src_line++;
455}
456