OSDN Git Service

PR fortran/33739
[pf3gnuchains/gcc-fork.git] / gcc / fortran / scanner.c
1 /* Character scanner.
2    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
3    Free Software Foundation, Inc.
4    Contributed by Andy Vaught
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* Set of subroutines to (ultimately) return the next character to the
23    various matching subroutines.  This file's job is to read files and
24    build up lines that are parsed by the parser.  This means that we
25    handle continuation lines and "include" lines.
26
27    The first thing the scanner does is to load an entire file into
28    memory.  We load the entire file into memory for a couple reasons.
29    The first is that we want to be able to deal with nonseekable input
30    (pipes, stdin) and there is a lot of backing up involved during
31    parsing.
32
33    The second is that we want to be able to print the locus of errors,
34    and an error on line 999999 could conflict with something on line
35    one.  Given nonseekable input, we've got to store the whole thing.
36
37    One thing that helps are the column truncation limits that give us
38    an upper bound on the size of individual lines.  We don't store the
39    truncated stuff.
40
41    From the scanner's viewpoint, the higher level subroutines ask for
42    new characters and do a lot of jumping backwards.  */
43
44 #include "config.h"
45 #include "system.h"
46 #include "gfortran.h"
47 #include "toplev.h"
48 #include "debug.h"
49 #include "flags.h"
50
51 /* Structure for holding module and include file search path.  */
52 typedef struct gfc_directorylist
53 {
54   char *path;
55   bool use_for_modules;
56   struct gfc_directorylist *next;
57 }
58 gfc_directorylist;
59
60 /* List of include file search directories.  */
61 static gfc_directorylist *include_dirs, *intrinsic_modules_dirs;
62
63 static gfc_file *file_head, *current_file;
64
65 static int continue_flag, end_flag, openmp_flag;
66 static int continue_count, continue_line;
67 static locus openmp_locus;
68
69 gfc_source_form gfc_current_form;
70 static gfc_linebuf *line_head, *line_tail;
71        
72 locus gfc_current_locus;
73 const char *gfc_source_file;
74 static FILE *gfc_src_file;
75 static char *gfc_src_preprocessor_lines[2];
76
77 extern int pedantic;
78
79 /* Main scanner initialization.  */
80
81 void
82 gfc_scanner_init_1 (void)
83 {
84   file_head = NULL;
85   line_head = NULL;
86   line_tail = NULL;
87
88   continue_count = 0;
89   continue_line = 0;
90
91   end_flag = 0;
92 }
93
94
95 /* Main scanner destructor.  */
96
97 void
98 gfc_scanner_done_1 (void)
99 {
100   gfc_linebuf *lb;
101   gfc_file *f;
102
103   while(line_head != NULL) 
104     {
105       lb = line_head->next;
106       gfc_free(line_head);
107       line_head = lb;
108     }
109      
110   while(file_head != NULL) 
111     {
112       f = file_head->next;
113       gfc_free(file_head->filename);
114       gfc_free(file_head);
115       file_head = f;    
116     }
117 }
118
119
120 /* Adds path to the list pointed to by list.  */
121
122 static void
123 add_path_to_list (gfc_directorylist **list, const char *path,
124                   bool use_for_modules)
125 {
126   gfc_directorylist *dir;
127   const char *p;
128
129   p = path;
130   while (*p == ' ' || *p == '\t')  /* someone might do "-I include" */
131     if (*p++ == '\0')
132       return;
133
134   dir = *list;
135   if (!dir)
136     dir = *list = gfc_getmem (sizeof (gfc_directorylist));
137   else
138     {
139       while (dir->next)
140         dir = dir->next;
141
142       dir->next = gfc_getmem (sizeof (gfc_directorylist));
143       dir = dir->next;
144     }
145
146   dir->next = NULL;
147   dir->use_for_modules = use_for_modules;
148   dir->path = gfc_getmem (strlen (p) + 2);
149   strcpy (dir->path, p);
150   strcat (dir->path, "/");      /* make '/' last character */
151 }
152
153
154 void
155 gfc_add_include_path (const char *path, bool use_for_modules)
156 {
157   add_path_to_list (&include_dirs, path, use_for_modules);
158 }
159
160
161 void
162 gfc_add_intrinsic_modules_path (const char *path)
163 {
164   add_path_to_list (&intrinsic_modules_dirs, path, true);
165 }
166
167
168 /* Release resources allocated for options.  */
169
170 void
171 gfc_release_include_path (void)
172 {
173   gfc_directorylist *p;
174
175   while (include_dirs != NULL)
176     {
177       p = include_dirs;
178       include_dirs = include_dirs->next;
179       gfc_free (p->path);
180       gfc_free (p);
181     }
182
183   while (intrinsic_modules_dirs != NULL)
184     {
185       p = intrinsic_modules_dirs;
186       intrinsic_modules_dirs = intrinsic_modules_dirs->next;
187       gfc_free (p->path);
188       gfc_free (p);
189     }
190
191   gfc_free (gfc_option.module_dir);
192 }
193
194
195 static FILE *
196 open_included_file (const char *name, gfc_directorylist *list, bool module)
197 {
198   char *fullname;
199   gfc_directorylist *p;
200   FILE *f;
201
202   for (p = list; p; p = p->next)
203     {
204       if (module && !p->use_for_modules)
205         continue;
206
207       fullname = (char *) alloca(strlen (p->path) + strlen (name) + 1);
208       strcpy (fullname, p->path);
209       strcat (fullname, name);
210
211       f = gfc_open_file (fullname);
212       if (f != NULL)
213         return f;
214     }
215
216   return NULL;
217 }
218
219
220 /* Opens file for reading, searching through the include directories
221    given if necessary.  If the include_cwd argument is true, we try
222    to open the file in the current directory first.  */
223
224 FILE *
225 gfc_open_included_file (const char *name, bool include_cwd, bool module)
226 {
227   FILE *f;
228
229   if (IS_ABSOLUTE_PATH (name))
230     return gfc_open_file (name);
231
232   if (include_cwd)
233     {
234       f = gfc_open_file (name);
235       if (f != NULL)
236         return f;
237     }
238
239   return open_included_file (name, include_dirs, module);
240 }
241
242 FILE *
243 gfc_open_intrinsic_module (const char *name)
244 {
245   if (IS_ABSOLUTE_PATH (name))
246     return gfc_open_file (name);
247
248   return open_included_file (name, intrinsic_modules_dirs, true);
249 }
250
251
252 /* Test to see if we're at the end of the main source file.  */
253
254 int
255 gfc_at_end (void)
256 {
257   return end_flag;
258 }
259
260
261 /* Test to see if we're at the end of the current file.  */
262
263 int
264 gfc_at_eof (void)
265 {
266   if (gfc_at_end ())
267     return 1;
268
269   if (line_head == NULL)
270     return 1;                   /* Null file */
271
272   if (gfc_current_locus.lb == NULL)
273     return 1;
274
275   return 0;
276 }
277
278
279 /* Test to see if we're at the beginning of a new line.  */
280
281 int
282 gfc_at_bol (void)
283 {
284   if (gfc_at_eof ())
285     return 1;
286
287   return (gfc_current_locus.nextc == gfc_current_locus.lb->line);
288 }
289
290
291 /* Test to see if we're at the end of a line.  */
292
293 int
294 gfc_at_eol (void)
295 {
296   if (gfc_at_eof ())
297     return 1;
298
299   return (*gfc_current_locus.nextc == '\0');
300 }
301
302
303 /* Advance the current line pointer to the next line.  */
304
305 void
306 gfc_advance_line (void)
307 {
308   if (gfc_at_end ())
309     return;
310
311   if (gfc_current_locus.lb == NULL) 
312     {
313       end_flag = 1;
314       return;
315     } 
316
317   if (gfc_current_locus.lb->next
318       && gfc_current_locus.lb->next->file != gfc_current_locus.lb->file)
319     {
320       if (gfc_current_locus.lb->next->file
321           && !gfc_current_locus.lb->next->dbg_emitted
322           && gfc_current_locus.lb->file->up == gfc_current_locus.lb->next->file)
323         {
324           /* We exit from an included file. */
325           (*debug_hooks->end_source_file)
326                 (gfc_linebuf_linenum (gfc_current_locus.lb->next));
327           gfc_current_locus.lb->next->dbg_emitted = true;
328         }
329       else if (gfc_current_locus.lb->next->file != gfc_current_locus.lb->file
330                && !gfc_current_locus.lb->next->dbg_emitted)
331         {
332           /* We enter into a new file.  */
333           (*debug_hooks->start_source_file)
334                 (gfc_linebuf_linenum (gfc_current_locus.lb),
335                  gfc_current_locus.lb->next->file->filename);
336           gfc_current_locus.lb->next->dbg_emitted = true;
337         }
338     }
339
340   gfc_current_locus.lb = gfc_current_locus.lb->next;
341
342   if (gfc_current_locus.lb != NULL)      
343     gfc_current_locus.nextc = gfc_current_locus.lb->line;
344   else 
345     {
346       gfc_current_locus.nextc = NULL;
347       end_flag = 1;
348     }       
349 }
350
351
352 /* Get the next character from the input, advancing gfc_current_file's
353    locus.  When we hit the end of the line or the end of the file, we
354    start returning a '\n' in order to complete the current statement.
355    No Fortran line conventions are implemented here.
356
357    Requiring explicit advances to the next line prevents the parse
358    pointer from being on the wrong line if the current statement ends
359    prematurely.  */
360
361 static int
362 next_char (void)
363 {
364   int c;
365   
366   if (gfc_current_locus.nextc == NULL)
367     return '\n';
368
369   c = (unsigned char) *gfc_current_locus.nextc++;
370   if (c == '\0')
371     {
372       gfc_current_locus.nextc--; /* Remain on this line.  */
373       c = '\n';
374     }
375
376   return c;
377 }
378
379
380 /* Skip a comment.  When we come here the parse pointer is positioned
381    immediately after the comment character.  If we ever implement
382    compiler directives withing comments, here is where we parse the
383    directive.  */
384
385 static void
386 skip_comment_line (void)
387 {
388   char c;
389
390   do
391     {
392       c = next_char ();
393     }
394   while (c != '\n');
395
396   gfc_advance_line ();
397 }
398
399
400 int
401 gfc_define_undef_line (void)
402 {
403   /* All lines beginning with '#' are either #define or #undef.  */
404   if (debug_info_level != DINFO_LEVEL_VERBOSE || gfc_peek_char () != '#')
405     return 0;
406
407   if (strncmp (gfc_current_locus.nextc, "#define ", 8) == 0)
408     (*debug_hooks->define) (gfc_linebuf_linenum (gfc_current_locus.lb),
409                             &(gfc_current_locus.nextc[8]));
410
411   if (strncmp (gfc_current_locus.nextc, "#undef ", 7) == 0)
412     (*debug_hooks->undef) (gfc_linebuf_linenum (gfc_current_locus.lb),
413                            &(gfc_current_locus.nextc[7]));
414
415   /* Skip the rest of the line.  */
416   skip_comment_line ();
417
418   return 1;
419 }
420
421
422 /* Comment lines are null lines, lines containing only blanks or lines
423    on which the first nonblank line is a '!'.
424    Return true if !$ openmp conditional compilation sentinel was
425    seen.  */
426
427 static bool
428 skip_free_comments (void)
429 {
430   locus start;
431   char c;
432   int at_bol;
433
434   for (;;)
435     {
436       at_bol = gfc_at_bol ();
437       start = gfc_current_locus;
438       if (gfc_at_eof ())
439         break;
440
441       do
442         c = next_char ();
443       while (gfc_is_whitespace (c));
444
445       if (c == '\n')
446         {
447           gfc_advance_line ();
448           continue;
449         }
450
451       if (c == '!')
452         {
453           /* If -fopenmp, we need to handle here 2 things:
454              1) don't treat !$omp as comments, but directives
455              2) handle OpenMP conditional compilation, where
456                 !$ should be treated as 2 spaces (for initial lines
457                 only if followed by space).  */
458           if (gfc_option.flag_openmp && at_bol)
459             {
460               locus old_loc = gfc_current_locus;
461               if (next_char () == '$')
462                 {
463                   c = next_char ();
464                   if (c == 'o' || c == 'O')
465                     {
466                       if (((c = next_char ()) == 'm' || c == 'M')
467                           && ((c = next_char ()) == 'p' || c == 'P'))
468                         {
469                           if ((c = next_char ()) == ' ' || continue_flag)
470                             {
471                               while (gfc_is_whitespace (c))
472                                 c = next_char ();
473                               if (c != '\n' && c != '!')
474                                 {
475                                   openmp_flag = 1;
476                                   openmp_locus = old_loc;
477                                   gfc_current_locus = start;
478                                   return false;
479                                 }
480                             }
481                           else
482                             gfc_warning_now ("!$OMP at %C starts a commented "
483                                              "line as it neither is followed "
484                                              "by a space nor is a "
485                                              "continuation line");
486                         }
487                       gfc_current_locus = old_loc;
488                       next_char ();
489                       c = next_char ();
490                     }
491                   if (continue_flag || c == ' ')
492                     {
493                       gfc_current_locus = old_loc;
494                       next_char ();
495                       openmp_flag = 0;
496                       return true;
497                     }
498                 }
499               gfc_current_locus = old_loc;
500             }
501           skip_comment_line ();
502           continue;
503         }
504
505       break;
506     }
507
508   if (openmp_flag && at_bol)
509     openmp_flag = 0;
510   gfc_current_locus = start;
511   return false;
512 }
513
514
515 /* Skip comment lines in fixed source mode.  We have the same rules as
516    in skip_free_comment(), except that we can have a 'c', 'C' or '*'
517    in column 1, and a '!' cannot be in column 6.  Also, we deal with
518    lines with 'd' or 'D' in column 1, if the user requested this.  */
519
520 static void
521 skip_fixed_comments (void)
522 {
523   locus start;
524   int col;
525   char c;
526
527   if (! gfc_at_bol ())
528     {
529       start = gfc_current_locus;
530       if (! gfc_at_eof ())
531         {
532           do
533             c = next_char ();
534           while (gfc_is_whitespace (c));
535
536           if (c == '\n')
537             gfc_advance_line ();
538           else if (c == '!')
539             skip_comment_line ();
540         }
541
542       if (! gfc_at_bol ())
543         {
544           gfc_current_locus = start;
545           return;
546         }
547     }
548
549   for (;;)
550     {
551       start = gfc_current_locus;
552       if (gfc_at_eof ())
553         break;
554
555       c = next_char ();
556       if (c == '\n')
557         {
558           gfc_advance_line ();
559           continue;
560         }
561
562       if (c == '!' || c == 'c' || c == 'C' || c == '*')
563         {
564           /* If -fopenmp, we need to handle here 2 things:
565              1) don't treat !$omp|c$omp|*$omp as comments, but directives
566              2) handle OpenMP conditional compilation, where
567                 !$|c$|*$ should be treated as 2 spaces if the characters
568                 in columns 3 to 6 are valid fixed form label columns
569                 characters.  */
570           if (gfc_option.flag_openmp)
571             {
572               if (next_char () == '$')
573                 {
574                   c = next_char ();
575                   if (c == 'o' || c == 'O')
576                     {
577                       if (((c = next_char ()) == 'm' || c == 'M')
578                           && ((c = next_char ()) == 'p' || c == 'P'))
579                         {
580                           c = next_char ();
581                           if (c != '\n'
582                               && ((openmp_flag && continue_flag)
583                                   || c == ' ' || c == '0'))
584                             {
585                               c = next_char ();
586                               while (gfc_is_whitespace (c))
587                                 c = next_char ();
588                               if (c != '\n' && c != '!')
589                                 {
590                                   /* Canonicalize to *$omp.  */
591                                   *start.nextc = '*';
592                                   openmp_flag = 1;
593                                   gfc_current_locus = start;
594                                   return;
595                                 }
596                             }
597                         }
598                     }
599                   else
600                     {
601                       int digit_seen = 0;
602
603                       for (col = 3; col < 6; col++, c = next_char ())
604                         if (c == ' ')
605                           continue;
606                         else if (c < '0' || c > '9')
607                           break;
608                         else
609                           digit_seen = 1;
610
611                       if (col == 6 && c != '\n'
612                           && ((continue_flag && !digit_seen)
613                               || c == ' ' || c == '0'))
614                         {
615                           gfc_current_locus = start;
616                           start.nextc[0] = ' ';
617                           start.nextc[1] = ' ';
618                           continue;
619                         }
620                     }
621                 }
622               gfc_current_locus = start;
623             }
624           skip_comment_line ();
625           continue;
626         }
627
628       if (gfc_option.flag_d_lines != -1 && (c == 'd' || c == 'D'))
629         {
630           if (gfc_option.flag_d_lines == 0)
631             {
632               skip_comment_line ();
633               continue;
634             }
635           else
636             *start.nextc = c = ' ';
637         }
638
639       col = 1;
640
641       while (gfc_is_whitespace (c))
642         {
643           c = next_char ();
644           col++;
645         }
646
647       if (c == '\n')
648         {
649           gfc_advance_line ();
650           continue;
651         }
652
653       if (col != 6 && c == '!')
654         {
655           skip_comment_line ();
656           continue;
657         }
658
659       break;
660     }
661
662   openmp_flag = 0;
663   gfc_current_locus = start;
664 }
665
666
667 /* Skips the current line if it is a comment.  */
668
669 void
670 gfc_skip_comments (void)
671 {
672   if (gfc_current_form == FORM_FREE)
673     skip_free_comments ();
674   else
675     skip_fixed_comments ();
676 }
677
678
679 /* Get the next character from the input, taking continuation lines
680    and end-of-line comments into account.  This implies that comment
681    lines between continued lines must be eaten here.  For higher-level
682    subroutines, this flattens continued lines into a single logical
683    line.  The in_string flag denotes whether we're inside a character
684    context or not.  */
685
686 int
687 gfc_next_char_literal (int in_string)
688 {
689   locus old_loc;
690   int i, c, prev_openmp_flag;
691
692   continue_flag = 0;
693
694 restart:
695   c = next_char ();
696   if (gfc_at_end ())
697     {
698       continue_count = 0;
699       return c;
700     }
701
702   if (gfc_current_form == FORM_FREE)
703     {
704       bool openmp_cond_flag;
705
706       if (!in_string && c == '!')
707         {
708           if (openmp_flag
709               && memcmp (&gfc_current_locus, &openmp_locus,
710                  sizeof (gfc_current_locus)) == 0)
711             goto done;
712
713           /* This line can't be continued */
714           do
715             {
716               c = next_char ();
717             }
718           while (c != '\n');
719
720           /* Avoid truncation warnings for comment ending lines.  */
721           gfc_current_locus.lb->truncated = 0;
722
723           goto done;
724         }
725
726       if (c != '&')
727         goto done;
728
729       /* If the next nonblank character is a ! or \n, we've got a
730          continuation line.  */
731       old_loc = gfc_current_locus;
732
733       c = next_char ();
734       while (gfc_is_whitespace (c))
735         c = next_char ();
736
737       /* Character constants to be continued cannot have commentary
738          after the '&'.  */
739
740       if (in_string && c != '\n')
741         {
742           gfc_current_locus = old_loc;
743           c = '&';
744           goto done;
745         }
746
747       if (c != '!' && c != '\n')
748         {
749           gfc_current_locus = old_loc;
750           c = '&';
751           goto done;
752         }
753
754       prev_openmp_flag = openmp_flag;
755       continue_flag = 1;
756       if (c == '!')
757         skip_comment_line ();
758       else
759         gfc_advance_line ();
760       
761       if (gfc_at_eof())
762         goto not_continuation;
763
764       /* We've got a continuation line.  If we are on the very next line after
765          the last continuation, increment the continuation line count and
766          check whether the limit has been exceeded.  */
767       if (gfc_linebuf_linenum (gfc_current_locus.lb) == continue_line + 1)
768         {
769           if (++continue_count == gfc_option.max_continue_free)
770             {
771               if (gfc_notification_std (GFC_STD_GNU) || pedantic)
772                 gfc_warning ("Limit of %d continuations exceeded in "
773                              "statement at %C", gfc_option.max_continue_free);
774             }
775         }
776       continue_line = gfc_linebuf_linenum (gfc_current_locus.lb);
777
778       /* Now find where it continues. First eat any comment lines.  */
779       openmp_cond_flag = skip_free_comments ();
780
781       if (prev_openmp_flag != openmp_flag)
782         {
783           gfc_current_locus = old_loc;
784           openmp_flag = prev_openmp_flag;
785           c = '&';
786           goto done;
787         }
788
789       /* Now that we have a non-comment line, probe ahead for the
790          first non-whitespace character.  If it is another '&', then
791          reading starts at the next character, otherwise we must back
792          up to where the whitespace started and resume from there.  */
793
794       old_loc = gfc_current_locus;
795
796       c = next_char ();
797       while (gfc_is_whitespace (c))
798         c = next_char ();
799
800       if (openmp_flag)
801         {
802           for (i = 0; i < 5; i++, c = next_char ())
803             {
804               gcc_assert (TOLOWER (c) == "!$omp"[i]);
805               if (i == 4)
806                 old_loc = gfc_current_locus;
807             }
808           while (gfc_is_whitespace (c))
809             c = next_char ();
810         }
811
812       if (c != '&')
813         {
814           if (in_string)
815             {
816               if (gfc_option.warn_ampersand)
817                 gfc_warning_now ("Missing '&' in continued character "
818                                  "constant at %C");
819               gfc_current_locus.nextc--;
820             }
821           /* Both !$omp and !$ -fopenmp continuation lines have & on the
822              continuation line only optionally.  */
823           else if (openmp_flag || openmp_cond_flag)
824             gfc_current_locus.nextc--;
825           else
826             {
827               c = ' ';
828               gfc_current_locus = old_loc;
829               goto done;
830             }
831         }
832     }
833   else
834     {
835       /* Fixed form continuation.  */
836       if (!in_string && c == '!')
837         {
838           /* Skip comment at end of line.  */
839           do
840             {
841               c = next_char ();
842             }
843           while (c != '\n');
844
845           /* Avoid truncation warnings for comment ending lines.  */
846           gfc_current_locus.lb->truncated = 0;
847         }
848
849       if (c != '\n')
850         goto done;
851
852       prev_openmp_flag = openmp_flag;
853       continue_flag = 1;
854       old_loc = gfc_current_locus;
855
856       gfc_advance_line ();
857       skip_fixed_comments ();
858
859       /* See if this line is a continuation line.  */
860       if (openmp_flag != prev_openmp_flag)
861         {
862           openmp_flag = prev_openmp_flag;
863           goto not_continuation;
864         }
865
866       if (!openmp_flag)
867         for (i = 0; i < 5; i++)
868           {
869             c = next_char ();
870             if (c != ' ')
871               goto not_continuation;
872           }
873       else
874         for (i = 0; i < 5; i++)
875           {
876             c = next_char ();
877             if (TOLOWER (c) != "*$omp"[i])
878               goto not_continuation;
879           }
880
881       c = next_char ();
882       if (c == '0' || c == ' ' || c == '\n')
883         goto not_continuation;
884
885       /* We've got a continuation line.  If we are on the very next line after
886          the last continuation, increment the continuation line count and
887          check whether the limit has been exceeded.  */
888       if (gfc_linebuf_linenum (gfc_current_locus.lb) == continue_line + 1)
889         {
890           if (++continue_count == gfc_option.max_continue_fixed)
891             {
892               if (gfc_notification_std (GFC_STD_GNU) || pedantic)
893                 gfc_warning ("Limit of %d continuations exceeded in "
894                              "statement at %C",
895                              gfc_option.max_continue_fixed);
896             }
897         }
898
899       if (continue_line < gfc_linebuf_linenum (gfc_current_locus.lb))
900         continue_line = gfc_linebuf_linenum (gfc_current_locus.lb);
901     }
902
903   /* Ready to read first character of continuation line, which might
904      be another continuation line!  */
905   goto restart;
906
907 not_continuation:
908   c = '\n';
909   gfc_current_locus = old_loc;
910
911 done:
912   if (c == '\n')
913     continue_count = 0;
914   continue_flag = 0;
915   return c;
916 }
917
918
919 /* Get the next character of input, folded to lowercase.  In fixed
920    form mode, we also ignore spaces.  When matcher subroutines are
921    parsing character literals, they have to call
922    gfc_next_char_literal().  */
923
924 int
925 gfc_next_char (void)
926 {
927   int c;
928
929   do
930     {
931       c = gfc_next_char_literal (0);
932     }
933   while (gfc_current_form == FORM_FIXED && gfc_is_whitespace (c));
934
935   return TOLOWER (c);
936 }
937
938
939 int
940 gfc_peek_char (void)
941 {
942   locus old_loc;
943   int c;
944
945   old_loc = gfc_current_locus;
946   c = gfc_next_char ();
947   gfc_current_locus = old_loc;
948
949   return c;
950 }
951
952
953 /* Recover from an error.  We try to get past the current statement
954    and get lined up for the next.  The next statement follows a '\n'
955    or a ';'.  We also assume that we are not within a character
956    constant, and deal with finding a '\'' or '"'.  */
957
958 void
959 gfc_error_recovery (void)
960 {
961   char c, delim;
962
963   if (gfc_at_eof ())
964     return;
965
966   for (;;)
967     {
968       c = gfc_next_char ();
969       if (c == '\n' || c == ';')
970         break;
971
972       if (c != '\'' && c != '"')
973         {
974           if (gfc_at_eof ())
975             break;
976           continue;
977         }
978       delim = c;
979
980       for (;;)
981         {
982           c = next_char ();
983
984           if (c == delim)
985             break;
986           if (c == '\n')
987             return;
988           if (c == '\\')
989             {
990               c = next_char ();
991               if (c == '\n')
992                 return;
993             }
994         }
995       if (gfc_at_eof ())
996         break;
997     }
998 }
999
1000
1001 /* Read ahead until the next character to be read is not whitespace.  */
1002
1003 void
1004 gfc_gobble_whitespace (void)
1005 {
1006   static int linenum = 0;
1007   locus old_loc;
1008   int c;
1009
1010   do
1011     {
1012       old_loc = gfc_current_locus;
1013       c = gfc_next_char_literal (0);
1014       /* Issue a warning for nonconforming tabs.  We keep track of the line
1015          number because the Fortran matchers will often back up and the same
1016          line will be scanned multiple times.  */
1017       if (!gfc_option.warn_tabs && c == '\t')
1018         {
1019 #ifdef USE_MAPPED_LOCATION
1020           int cur_linenum = LOCATION_LINE (gfc_current_locus.lb->location);
1021 #else
1022           int cur_linenum = gfc_current_locus.lb->linenum;
1023 #endif
1024           if (cur_linenum != linenum)
1025             {
1026               linenum = cur_linenum;
1027               gfc_warning_now ("Nonconforming tab character at %C");
1028             }
1029         }
1030     }
1031   while (gfc_is_whitespace (c));
1032
1033   gfc_current_locus = old_loc;
1034 }
1035
1036
1037 /* Load a single line into pbuf.
1038
1039    If pbuf points to a NULL pointer, it is allocated.
1040    We truncate lines that are too long, unless we're dealing with
1041    preprocessor lines or if the option -ffixed-line-length-none is set,
1042    in which case we reallocate the buffer to fit the entire line, if
1043    need be.
1044    In fixed mode, we expand a tab that occurs within the statement
1045    label region to expand to spaces that leave the next character in
1046    the source region.
1047    load_line returns whether the line was truncated.
1048
1049    NOTE: The error machinery isn't available at this point, so we can't
1050          easily report line and column numbers consistent with other 
1051          parts of gfortran.  */
1052
1053 static int
1054 load_line (FILE *input, char **pbuf, int *pbuflen)
1055 {
1056   static int linenum = 0, current_line = 1;
1057   int c, maxlen, i, preprocessor_flag, buflen = *pbuflen;
1058   int trunc_flag = 0, seen_comment = 0;
1059   int seen_printable = 0, seen_ampersand = 0;
1060   char *buffer;
1061
1062   /* Determine the maximum allowed line length.  */
1063   if (gfc_current_form == FORM_FREE)
1064     maxlen = gfc_option.free_line_length;
1065   else if (gfc_current_form == FORM_FIXED)
1066     maxlen = gfc_option.fixed_line_length;
1067   else
1068     maxlen = 72;
1069
1070   if (*pbuf == NULL)
1071     {
1072       /* Allocate the line buffer, storing its length into buflen.
1073          Note that if maxlen==0, indicating that arbitrary-length lines
1074          are allowed, the buffer will be reallocated if this length is
1075          insufficient; since 132 characters is the length of a standard
1076          free-form line, we use that as a starting guess.  */
1077       if (maxlen > 0)
1078         buflen = maxlen;
1079       else
1080         buflen = 132;
1081
1082       *pbuf = gfc_getmem (buflen + 1);
1083     }
1084
1085   i = 0;
1086   buffer = *pbuf;
1087
1088   preprocessor_flag = 0;
1089   c = getc (input);
1090   if (c == '#')
1091     /* In order to not truncate preprocessor lines, we have to
1092        remember that this is one.  */
1093     preprocessor_flag = 1;
1094   ungetc (c, input);
1095
1096   for (;;)
1097     {
1098       c = getc (input);
1099
1100       if (c == EOF)
1101         break;
1102       if (c == '\n')
1103         {
1104           /* Check for illegal use of ampersand. See F95 Standard 3.3.1.3.  */
1105           if (gfc_current_form == FORM_FREE 
1106               && !seen_printable && seen_ampersand)
1107             {
1108               if (pedantic)
1109                 gfc_error_now ("'&' not allowed by itself in line %d",
1110                                current_line);
1111               else
1112                 gfc_warning_now ("'&' not allowed by itself in line %d",
1113                                  current_line);
1114             }
1115           break;
1116         }
1117
1118       if (c == '\r')
1119         continue;               /* Gobble characters.  */
1120       if (c == '\0')
1121         continue;
1122
1123       if (c == '&')
1124         {
1125           if (seen_ampersand)
1126             seen_ampersand = 0;
1127           else
1128             seen_ampersand = 1;
1129         }
1130
1131       if ((c != '&' && c != '!') || (c == '!' && !seen_ampersand))
1132         seen_printable = 1;
1133
1134       /* Is this a fixed-form comment?  */
1135       if (gfc_current_form == FORM_FIXED && i == 0
1136           && (c == '*' || c == 'c' || c == 'd'))
1137         seen_comment = 1;
1138
1139       if (gfc_current_form == FORM_FIXED && c == '\t' && i <= 6)
1140         {
1141           if (!gfc_option.warn_tabs && seen_comment == 0
1142               && current_line != linenum)
1143             {
1144               linenum = current_line;
1145               gfc_warning_now ("Nonconforming tab character in column 1 "
1146                                "of line %d", linenum);
1147             }
1148
1149           while (i <= 6)
1150             {
1151               *buffer++ = ' ';
1152               i++;
1153             }
1154
1155           continue;
1156         }
1157
1158       *buffer++ = c;
1159       i++;
1160
1161       if (maxlen == 0 || preprocessor_flag)
1162         {
1163           if (i >= buflen)
1164             {
1165               /* Reallocate line buffer to double size to hold the
1166                 overlong line.  */
1167               buflen = buflen * 2;
1168               *pbuf = xrealloc (*pbuf, buflen + 1);
1169               buffer = (*pbuf) + i;
1170             }
1171         }
1172       else if (i >= maxlen)
1173         {
1174           /* Truncate the rest of the line.  */
1175           for (;;)
1176             {
1177               c = getc (input);
1178               if (c == '\n' || c == EOF)
1179                 break;
1180
1181               trunc_flag = 1;
1182             }
1183
1184           ungetc ('\n', input);
1185         }
1186     }
1187
1188   /* Pad lines to the selected line length in fixed form.  */
1189   if (gfc_current_form == FORM_FIXED
1190       && gfc_option.fixed_line_length != 0
1191       && !preprocessor_flag
1192       && c != EOF)
1193     {
1194       while (i++ < maxlen)
1195         *buffer++ = ' ';
1196     }
1197
1198   *buffer = '\0';
1199   *pbuflen = buflen;
1200   current_line++;
1201
1202   return trunc_flag;
1203 }
1204
1205
1206 /* Get a gfc_file structure, initialize it and add it to
1207    the file stack.  */
1208
1209 static gfc_file *
1210 get_file (const char *name, enum lc_reason reason ATTRIBUTE_UNUSED)
1211 {
1212   gfc_file *f;
1213
1214   f = gfc_getmem (sizeof (gfc_file));
1215
1216   f->filename = gfc_getmem (strlen (name) + 1);
1217   strcpy (f->filename, name);
1218
1219   f->next = file_head;
1220   file_head = f;
1221
1222   f->included_by = current_file;
1223   if (current_file != NULL)
1224     f->inclusion_line = current_file->line;
1225
1226 #ifdef USE_MAPPED_LOCATION
1227   linemap_add (line_table, reason, false, f->filename, 1);
1228 #endif
1229
1230   return f;
1231 }
1232
1233 /* Deal with a line from the C preprocessor. The
1234    initial octothorp has already been seen.  */
1235
1236 static void
1237 preprocessor_line (char *c)
1238 {
1239   bool flag[5];
1240   int i, line;
1241   char *filename;
1242   gfc_file *f;
1243   int escaped, unescape;
1244
1245   c++;
1246   while (*c == ' ' || *c == '\t')
1247     c++;
1248
1249   if (*c < '0' || *c > '9')
1250     goto bad_cpp_line;
1251
1252   line = atoi (c);
1253
1254   c = strchr (c, ' ');
1255   if (c == NULL)
1256     {
1257       /* No file name given.  Set new line number.  */
1258       current_file->line = line;
1259       return;
1260     }
1261
1262   /* Skip spaces.  */
1263   while (*c == ' ' || *c == '\t')
1264     c++;
1265
1266   /* Skip quote.  */
1267   if (*c != '"')
1268     goto bad_cpp_line;
1269   ++c;
1270
1271   filename = c;
1272
1273   /* Make filename end at quote.  */
1274   unescape = 0;
1275   escaped = false;
1276   while (*c && ! (!escaped && *c == '"'))
1277     {
1278       if (escaped)
1279         escaped = false;
1280       else if (*c == '\\')
1281         {
1282           escaped = true;
1283           unescape++;
1284         }
1285       ++c;
1286     }
1287
1288   if (! *c)
1289     /* Preprocessor line has no closing quote.  */
1290     goto bad_cpp_line;
1291
1292   *c++ = '\0';
1293
1294   /* Undo effects of cpp_quote_string.  */
1295   if (unescape)
1296     {
1297       char *s = filename;
1298       char *d = gfc_getmem (c - filename - unescape);
1299
1300       filename = d;
1301       while (*s)
1302         {
1303           if (*s == '\\')
1304             *d++ = *++s;
1305           else
1306             *d++ = *s;
1307           s++;
1308         }
1309       *d = '\0';
1310     }
1311
1312   /* Get flags.  */
1313
1314   flag[1] = flag[2] = flag[3] = flag[4] = false;
1315
1316   for (;;)
1317     {
1318       c = strchr (c, ' ');
1319       if (c == NULL)
1320         break;
1321
1322       c++;
1323       i = atoi (c);
1324
1325       if (1 <= i && i <= 4)
1326         flag[i] = true;
1327     }
1328
1329   /* Interpret flags.  */
1330
1331   if (flag[1]) /* Starting new file.  */
1332     {
1333       f = get_file (filename, LC_RENAME);
1334       f->up = current_file;
1335       current_file = f;
1336     }
1337
1338   if (flag[2]) /* Ending current file.  */
1339     {
1340       if (!current_file->up
1341           || strcmp (current_file->up->filename, filename) != 0)
1342         {
1343           gfc_warning_now ("%s:%d: file %s left but not entered",
1344                            current_file->filename, current_file->line,
1345                            filename);
1346           if (unescape)
1347             gfc_free (filename);
1348           return;
1349         }
1350
1351       current_file = current_file->up;
1352 #ifdef USE_MAPPED_LOCATION
1353       linemap_add (line_table, LC_RENAME, false, current_file->filename,
1354                    current_file->line);
1355 #endif
1356     }
1357
1358   /* The name of the file can be a temporary file produced by
1359      cpp. Replace the name if it is different.  */
1360
1361   if (strcmp (current_file->filename, filename) != 0)
1362     {
1363       gfc_free (current_file->filename);
1364       current_file->filename = gfc_getmem (strlen (filename) + 1);
1365       strcpy (current_file->filename, filename);
1366     }
1367
1368   /* Set new line number.  */
1369   current_file->line = line;
1370   if (unescape)
1371     gfc_free (filename);
1372   return;
1373
1374  bad_cpp_line:
1375   gfc_warning_now ("%s:%d: Illegal preprocessor directive",
1376                    current_file->filename, current_file->line);
1377   current_file->line++;
1378 }
1379
1380
1381 static try load_file (const char *, bool);
1382
1383 /* include_line()-- Checks a line buffer to see if it is an include
1384    line.  If so, we call load_file() recursively to load the included
1385    file.  We never return a syntax error because a statement like
1386    "include = 5" is perfectly legal.  We return false if no include was
1387    processed or true if we matched an include.  */
1388
1389 static bool
1390 include_line (char *line)
1391 {
1392   char quote, *c, *begin, *stop;
1393
1394   c = line;
1395
1396   if (gfc_option.flag_openmp)
1397     {
1398       if (gfc_current_form == FORM_FREE)
1399         {
1400           while (*c == ' ' || *c == '\t')
1401             c++;
1402           if (*c == '!' && c[1] == '$' && (c[2] == ' ' || c[2] == '\t'))
1403             c += 3;
1404         }
1405       else
1406         {
1407           if ((*c == '!' || *c == 'c' || *c == 'C' || *c == '*')
1408               && c[1] == '$' && (c[2] == ' ' || c[2] == '\t'))
1409             c += 3;
1410         }
1411     }
1412
1413   while (*c == ' ' || *c == '\t')
1414     c++;
1415
1416   if (strncasecmp (c, "include", 7))
1417       return false;
1418
1419   c += 7;
1420   while (*c == ' ' || *c == '\t')
1421     c++;
1422
1423   /* Find filename between quotes.  */
1424   
1425   quote = *c++;
1426   if (quote != '"' && quote != '\'')
1427     return false;
1428
1429   begin = c;
1430
1431   while (*c != quote && *c != '\0')
1432     c++;
1433
1434   if (*c == '\0')
1435     return false;
1436
1437   stop = c++;
1438   
1439   while (*c == ' ' || *c == '\t')
1440     c++;
1441
1442   if (*c != '\0' && *c != '!')
1443     return false;
1444
1445   /* We have an include line at this point.  */
1446
1447   *stop = '\0'; /* It's ok to trash the buffer, as this line won't be
1448                    read by anything else.  */
1449
1450   load_file (begin, false);
1451   return true;
1452 }
1453
1454
1455 /* Load a file into memory by calling load_line until the file ends.  */
1456
1457 static try
1458 load_file (const char *filename, bool initial)
1459 {
1460   char *line;
1461   gfc_linebuf *b;
1462   gfc_file *f;
1463   FILE *input;
1464   int len, line_len;
1465   bool first_line;
1466
1467   for (f = current_file; f; f = f->up)
1468     if (strcmp (filename, f->filename) == 0)
1469       {
1470         gfc_error_now ("File '%s' is being included recursively", filename);
1471         return FAILURE;
1472       }
1473
1474   if (initial)
1475     {
1476       if (gfc_src_file)
1477         {
1478           input = gfc_src_file;
1479           gfc_src_file = NULL;
1480         }
1481       else
1482         input = gfc_open_file (filename);
1483       if (input == NULL)
1484         {
1485           gfc_error_now ("Can't open file '%s'", filename);
1486           return FAILURE;
1487         }
1488     }
1489   else
1490     {
1491       input = gfc_open_included_file (filename, false, false);
1492       if (input == NULL)
1493         {
1494           gfc_error_now ("Can't open included file '%s'", filename);
1495           return FAILURE;
1496         }
1497     }
1498
1499   /* Load the file.  */
1500
1501   f = get_file (filename, initial ? LC_RENAME : LC_ENTER);
1502   f->up = current_file;
1503   current_file = f;
1504   current_file->line = 1;
1505   line = NULL;
1506   line_len = 0;
1507   first_line = true;
1508
1509   if (initial && gfc_src_preprocessor_lines[0])
1510     {
1511       preprocessor_line (gfc_src_preprocessor_lines[0]);
1512       gfc_free (gfc_src_preprocessor_lines[0]);
1513       gfc_src_preprocessor_lines[0] = NULL;
1514       if (gfc_src_preprocessor_lines[1])
1515         {
1516           preprocessor_line (gfc_src_preprocessor_lines[1]);
1517           gfc_free (gfc_src_preprocessor_lines[1]);
1518           gfc_src_preprocessor_lines[1] = NULL;
1519         }
1520     }
1521
1522   for (;;)
1523     {
1524       int trunc = load_line (input, &line, &line_len);
1525
1526       len = strlen (line);
1527       if (feof (input) && len == 0)
1528         break;
1529
1530       /* If this is the first line of the file, it can contain a byte
1531          order mark (BOM), which we will ignore:
1532            FF FE is UTF-16 little endian,
1533            FE FF is UTF-16 big endian,
1534            EF BB BF is UTF-8.  */
1535       if (first_line
1536           && ((line_len >= 2 && line[0] == '\xFF' && line[1] == '\xFE')
1537               || (line_len >= 2 && line[0] == '\xFE' && line[1] == '\xFF')
1538               || (line_len >= 3 && line[0] == '\xEF' && line[1] == '\xBB'
1539                   && line[2] == '\xBF')))
1540         {
1541           int n = line[1] == '\xBB' ? 3 : 2;
1542           char * new = gfc_getmem (line_len);
1543
1544           strcpy (new, line + n);
1545           gfc_free (line);
1546           line = new;
1547           len -= n;
1548         }
1549
1550       /* There are three things this line can be: a line of Fortran
1551          source, an include line or a C preprocessor directive.  */
1552
1553       if (line[0] == '#')
1554         {
1555           /* When -g3 is specified, it's possible that we emit #define
1556              and #undef lines, which we need to pass to the middle-end
1557              so that it can emit correct debug info.  */
1558           if (debug_info_level == DINFO_LEVEL_VERBOSE
1559               && (strncmp (line, "#define ", 8) == 0
1560                   || strncmp (line, "#undef ", 7) == 0))
1561             ;
1562           else
1563             {
1564               preprocessor_line (line);
1565               continue;
1566             }
1567         }
1568
1569       /* Preprocessed files have preprocessor lines added before the byte
1570          order mark, so first_line is not about the first line of the file
1571          but the first line that's not a preprocessor line.  */
1572       first_line = false;
1573
1574       if (include_line (line))
1575         {
1576           current_file->line++;
1577           continue;
1578         }
1579
1580       /* Add line.  */
1581
1582       b = gfc_getmem (gfc_linebuf_header_size + len + 1);
1583
1584 #ifdef USE_MAPPED_LOCATION
1585       b->location
1586         = linemap_line_start (line_table, current_file->line++, 120);
1587 #else
1588       b->linenum = current_file->line++;
1589 #endif
1590       b->file = current_file;
1591       b->truncated = trunc;
1592       strcpy (b->line, line);
1593
1594       if (line_head == NULL)
1595         line_head = b;
1596       else
1597         line_tail->next = b;
1598
1599       line_tail = b;
1600     }
1601
1602   /* Release the line buffer allocated in load_line.  */
1603   gfc_free (line);
1604
1605   fclose (input);
1606
1607   current_file = current_file->up;
1608 #ifdef USE_MAPPED_LOCATION
1609   linemap_add (line_table, LC_LEAVE, 0, NULL, 0);
1610 #endif
1611   return SUCCESS;
1612 }
1613
1614
1615 /* Open a new file and start scanning from that file. Returns SUCCESS
1616    if everything went OK, FAILURE otherwise.  If form == FORM_UKNOWN
1617    it tries to determine the source form from the filename, defaulting
1618    to free form.  */
1619
1620 try
1621 gfc_new_file (void)
1622 {
1623   try result;
1624
1625   result = load_file (gfc_source_file, true);
1626
1627   gfc_current_locus.lb = line_head;
1628   gfc_current_locus.nextc = (line_head == NULL) ? NULL : line_head->line;
1629
1630 #if 0 /* Debugging aid.  */
1631   for (; line_head; line_head = line_head->next)
1632     gfc_status ("%s:%3d %s\n",
1633 #ifdef USE_MAPPED_LOCATION
1634                 LOCATION_FILE (line_head->location),
1635                 LOCATION_LINE (line_head->location),
1636 #else
1637                 line_head->file->filename, 
1638                 line_head->linenum,
1639 #endif
1640                 line_head->line);
1641
1642   exit (0);
1643 #endif
1644
1645   return result;
1646 }
1647
1648 static char *
1649 unescape_filename (const char *ptr)
1650 {
1651   const char *p = ptr, *s;
1652   char *d, *ret;
1653   int escaped, unescape = 0;
1654
1655   /* Make filename end at quote.  */
1656   escaped = false;
1657   while (*p && ! (! escaped && *p == '"'))
1658     {
1659       if (escaped)
1660         escaped = false;
1661       else if (*p == '\\')
1662         {
1663           escaped = true;
1664           unescape++;
1665         }
1666       ++p;
1667     }
1668
1669   if (!*p || p[1])
1670     return NULL;
1671
1672   /* Undo effects of cpp_quote_string.  */
1673   s = ptr;
1674   d = gfc_getmem (p + 1 - ptr - unescape);
1675   ret = d;
1676
1677   while (s != p)
1678     {
1679       if (*s == '\\')
1680         *d++ = *++s;
1681       else
1682         *d++ = *s;
1683       s++;
1684     }
1685   *d = '\0';
1686   return ret;
1687 }
1688
1689 /* For preprocessed files, if the first tokens are of the form # NUM.
1690    handle the directives so we know the original file name.  */
1691
1692 const char *
1693 gfc_read_orig_filename (const char *filename, const char **canon_source_file)
1694 {
1695   int c, len;
1696   char *dirname;
1697
1698   gfc_src_file = gfc_open_file (filename);
1699   if (gfc_src_file == NULL)
1700     return NULL;
1701
1702   c = getc (gfc_src_file);
1703   ungetc (c, gfc_src_file);
1704
1705   if (c != '#')
1706     return NULL;
1707
1708   len = 0;
1709   load_line (gfc_src_file, &gfc_src_preprocessor_lines[0], &len);
1710
1711   if (strncmp (gfc_src_preprocessor_lines[0], "# 1 \"", 5) != 0)
1712     return NULL;
1713
1714   filename = unescape_filename (gfc_src_preprocessor_lines[0] + 5);
1715   if (filename == NULL)
1716     return NULL;
1717
1718   c = getc (gfc_src_file);
1719   ungetc (c, gfc_src_file);
1720
1721   if (c != '#')
1722     return filename;
1723
1724   len = 0;
1725   load_line (gfc_src_file, &gfc_src_preprocessor_lines[1], &len);
1726
1727   if (strncmp (gfc_src_preprocessor_lines[1], "# 1 \"", 5) != 0)
1728     return filename;
1729
1730   dirname = unescape_filename (gfc_src_preprocessor_lines[1] + 5);
1731   if (dirname == NULL)
1732     return filename;
1733
1734   len = strlen (dirname);
1735   if (len < 3 || dirname[len - 1] != '/' || dirname[len - 2] != '/')
1736     {
1737       gfc_free (dirname);
1738       return filename;
1739     }
1740   dirname[len - 2] = '\0';
1741   set_src_pwd (dirname);
1742
1743   if (! IS_ABSOLUTE_PATH (filename))
1744     {
1745       char *p = gfc_getmem (len + strlen (filename));
1746
1747       memcpy (p, dirname, len - 2);
1748       p[len - 2] = '/';
1749       strcpy (p + len - 1, filename);
1750       *canon_source_file = p;
1751     }
1752
1753   gfc_free (dirname);
1754   return filename;
1755 }