OSDN Git Service

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