OSDN Git Service

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