makef90depends.in 74.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! @PERL@
#
# Please run
#   perlpod makef90depends
# for usage information.
#
# Print Makefile-style dependencies for objects derived from Fortran
# 90 source files, i.e. if a.f90 includes a line like
#
#  use b
#
# and b.f90 contains a line like
#
#  module b
#
# then the following will be emitted:
#
#  a.o: b.o
#
# The script tries to produce the same for include and #include
# directives, but might infer both, too many and too few dependencies
# because preprocessor conditionals are currently not evaluated
# correctly and includes are not followed recursively.
#
# Author: Thomas Jahns <jahns@dkrz.de>, 2009.
# Based on createMakefile.pl by by Uwe Schulzweida <schulzweida@dkrz.de>
#
use strict;
use warnings;

use Data::Dumper ();
use File::Spec ();
use File::Temp ();
use Getopt::Long ();

my ($debug, $verbose, $dumpCppKeys) = (0, 0, undef);
my (@includeDirs, %defines, @ignoredSysIncludes, @ignoredModules);
my ($objDepOut, $objectSuffix, $stripObjDirname) = (1, '.o', 0);
my @nameSubst;
parseOptions();
foreach my $transformRule (@nameSubst)
{
   my $trCopy = $transformRule;
   $transformRule = [ $transformRule =~ m{([^=]+)=(.*)} ];
   die('Malformed rule of transformation: ', $trCopy, "\n")
       if (@$transformRule != 2);
}

push @nameSubst, ['\.f90$', $objectSuffix];

#print STDERR Data::Dumper->Dump([\@nameSubst], ['nameSubst']), "\n";
#print STDERR Data::Dumper->Dump([\%defines], ['defines']), "\n";

# filter duplicate filenames, duplicate dependencies make no sense
my @srcs;
pushUnique(\@srcs, @ARGV);


MakeDependsf90mod({ 'includePaths' => \@includeDirs,
                    'defines' => \%defines,
                    'nameSubst' => \@nameSubst,
                    'stripObjDirname' => $stripObjDirname,
                    'ignoredSysIncludes' => \@ignoredSysIncludes,
                    'ignoredModules' => \@ignoredModules,
                    'dumpCppKeys' => $dumpCppKeys,
                  }, @srcs);

sub uniq {
   my (%seen);
   return grep { if (!exists $seen{$_}) { $seen{$_} = 1; } else { 0; } } @_;
}

#
# &MakeDependsf90([optHASH, ] [FILE...]);
#
sub MakeDependsf90mod {
   my (%moduleProvide, %incs, %moduleUse, $objfile, $fh, @incDirs, @nameSubst,
       @ignoredSysIncludes, @ignoredModules, $globalDefines, $dumpCppKeys);
   my %cppKeys;
   my $optArgs = {};
   my ($stripObjDirname) = (0);
   local $_;
   my @srcs = @_;
   if (ref($srcs[0]) eq 'HASH')
   {
      $optArgs = shift @srcs;
      @nameSubst = @{$optArgs->{'nameSubst'}}
          if (exists($optArgs->{'nameSubst'}));
#      print STDERR Data::Dumper->Dump([\@nameSubst], ['nameSubst']);
      $stripObjDirname = $optArgs->{'stripObjDirname'}
          if (exists($optArgs->{'stripObjDirname'}));
      @ignoredSysIncludes = @{$optArgs->{'ignoredSysIncludes'}}
          if (exists($optArgs->{'ignoredSysIncludes'}));
      @ignoredModules = @{$optArgs->{'ignoredModules'}}
          if (exists($optArgs->{'ignoredModules'}));
      $globalDefines = $optArgs->{'defines'}
          if (exists($optArgs->{'defines'}));
      $dumpCppKeys = exists($optArgs->{'dumpCppKeys'})?$optArgs->{'dumpCppKeys'}:0;
      push(@incDirs, @{$optArgs->{'includePaths'}});
   }
   print(STDERR 'include paths: ', join(':', @incDirs), "\n") if $debug;
   #
   # Associate each module with the name of the file that contains it
   #
   foreach my $srcfile (@srcs) {
      close($fh) if defined($fh);
      open($fh, $srcfile) or die('Cannot open ', $srcfile, ': ');
      $incs{$srcfile} = [];
      $moduleUse{$srcfile} = [];
      my %localDefines = %$globalDefines;
      my @predicateLevels = ({'ignored' => 0});
      my $ignored = 0;
      while (<$fh>) {
         $_ = transliterateTrigraphs($_);
         while (m{(\\)$}x)
         {
            # adjoin continuation lines
            my ($contLine, $continuation);
            $continuation = $1;
            while (defined($continuation))
            {
               my $contLine = <$fh>;
               if (defined($contLine))
               {
                  ($contLine, $continuation) = $contLine =~ m{^(.*?)(\\)?$}x;
                  $_ .= $contLine;
               }
            }
         }
         if (m{^\s*#+(if|ifdef|ifndef|endif|else)\s+(.*?)\s*$})
         {
            my ($clause, $predicate) = ($1, $2);
            print(STDERR 'Investigating ', $clause, ' ', $predicate, ' at ',
                  $srcfile, ', line ', $., "\n") if $debug > 1;
            if ($clause eq 'endif')
            {
               die('#endif without opening #if at line ', $.,
                   ' of ', $srcfile, "\n")
                   if (@predicateLevels < 2);
               print(STDERR Data::Dumper->Dump([\@predicateLevels],
                                               ['predicatelevels']))
                   if $debug > 1;
               pop(@predicateLevels);
               $ignored = $predicateLevels[-1]{'ignored'};
            }
            elsif ($clause eq 'else')
            {
               die('#else without opening #if at line ', $.,
                   ' of ', $srcfile, "\n")
                   if (@predicateLevels < 2);
               $ignored = ($predicateLevels[-1]{'predValue'}
                           or $predicateLevels[-2]{'ignored'});
            }
            else
            {
               if ($clause eq 'if') {
                  my @cppKeys;
                  my $predValue
                      = evaluatePreProcExpression($predicate,
                                                  \%localDefines, \@cppKeys,
                                                  !$objDepOut);
                  my $newIgnored = (!$predValue or $ignored);
                  push(@predicateLevels, { 'ignored' => $newIgnored,
                                           'predValue' => $predValue,
                                           'line' => $. });
                  $ignored = $newIgnored;
                  foreach my $key (@cppKeys)
                  {
                     haPush(\%cppKeys, $key, $srcfile);
                  }
               }
               elsif (($clause eq 'ifdef') or ($clause eq 'ifndef'))
               {
                  my $predValue = 1;
                  die('Malformed predicate: ', $clause, ' ', $predicate)
                      if (not validPreProcSym($predicate));
                  if ($objDepOut)
                  {
                     insertDefinitionOnDemand(\%localDefines, $predicate)
                         if (!exists($localDefines{$predicate}));
                     $predValue = defined($localDefines{$predicate});
                  }
                  $predValue = !$predValue if ($clause eq 'ifndef');
                  my $newIgnored = (!$predValue or $ignored);
                  push(@predicateLevels, { 'ignored' => $newIgnored,
                                           'predValue' => $predValue,
                                           'line' => $. });
                  $ignored = $newIgnored;
                  haPush(\%cppKeys, $predicate, $srcfile);
               }
            }
            print(STDERR ($ignored?'Ignoring':'Evaluating'), ' upcoming text.',
                  "\n") if $debug > 1;
         }
         elsif (!$ignored)
         {
            if (m{^\s*\#+(?:define)
                  \s+([A-Za-z_]\w*)
                  (\(\s*[A-Za-z_]\w*(?:\s*,[A-Za-z_]\w*)*\s*\))?
                  \s+(.*?)\s*$}x)
            {
               my ($preProcSym, $args, $definition)
                   = ($1, $2, $3);
               $localDefines{$preProcSym} = parseDefinition($args, $definition,
                                                            $srcfile, $.);
               print(STDERR 'Intern\'ed definition ',
                     $localDefines{$preProcSym}, $args?():('(', $args, ')'),
                     $definition, "\n");
            }
            elsif (m{^\s*#+(?:undef)\s+([A-Za-z_]\w*)\s*(.*)?$})
            {
               my ($preProcSym, $trail) = ($1, $2);
               $localDefines{$preProcSym} = undef;
               warn('Trailing garbage on undef line ',
                    $., ' of ', $srcfile, ': ', $trail)
                   if defined($trail);
            }
            elsif(m{^\s*module\s+([^\s!]+)}i)
            {
               my $moduleName = lc($1);
               $moduleProvide{$moduleName}
                   = transformFilename($optArgs, $srcfile);
            }
            elsif (/^\s*#*include\s+(["\'])(.+)?\1/i)
            {
               pushUnique($incs{$srcfile}, $2);
            }
            elsif (/^\s*use\s+([^\s,!]+)/i)
            {
               pushUnique($moduleUse{$srcfile}, lc($1));
            }
         }
      }
      die('Unbalanced #if at line ', $predicateLevels[-1]{'line'},
          ' of ', $srcfile, "\n")
          if @predicateLevels > 2;
   }
#   print Data::Dumper->Dump([\%moduleUse, \%moduleProvide],
#                            ['moduleUse', 'moduleProvide']);
   #
   # Print the dependencies of each file that has one or more include's or
   # references one or more modules
   #
   if ($objDepOut)
   {
      foreach my $srcfile (@srcs) {
      my $objfile = transformFilename($optArgs, $srcfile);
      {
         print(STDERR $srcfile, ':', "\n",
               Data::Dumper->Dump([$incs{$srcfile}],
                                  ['incs'])) if ($debug > 1);
         @{$incs{$srcfile}} = grep { my $include = $_ ;
                                     !grep { $_ eq $include }
                                         @ignoredSysIncludes }
             @{$incs{$srcfile}};;
         my @locatedIncludes =
             map { findRelFile($_, @incDirs, File::Spec->curdir()) }
                 @{$incs{$srcfile}};
         print(STDERR $srcfile, ':', "\n",
               Data::Dumper->Dump([$incs{$srcfile}, \@locatedIncludes],
                                  ['incs', 'located'])) if ($debug > 1);
         if (grep { !defined($_) } @locatedIncludes) {
            for(my $i = 0; $i < @{$incs{$srcfile}}; ++$i) {
               warn $srcfile, ': include file ', $incs{$srcfile}[$i],
                   " not found\n" if (!defined($locatedIncludes[$i]));
            }
         }
         @{$incs{$srcfile}} = grep { defined($_) } @locatedIncludes;
      }
      # filter self-referential module use
      @{$moduleUse{$srcfile}} =
          grep { !(exists($moduleProvide{$_}) and
                   $objfile eq $moduleProvide{$_}) } @{$moduleUse{$srcfile}};
      if (@{$incs{$srcfile}} + @{$moduleUse{$srcfile}}) {
         print $objfile, ':';
         {
            my @notFound =
                grep { my $module = $_; !exists $moduleProvide{$_}
                           and not grep { $module eq $_ } @ignoredModules }
                @{$moduleUse{$srcfile}};
            warn $srcfile, ': module(s) ', join(', ', @notFound),
                " not found\n" if @notFound;
         }
         my @dependencies =
             map { $moduleProvide{$_} }
                 (grep { exists $moduleProvide{$_} } (@{$moduleUse{$srcfile}}));
         push @dependencies, @{$incs{$srcfile}};
         @dependencies = uniq(sort(@dependencies));
         printLFEscapeLineWrap({ 'printed' => length($objfile) + 1},
                               @dependencies, uniq(@{$incs{$srcfile}}));
         print "\n";
      }
   }}
   if (defined($dumpCppKeys))
   {
      my ($dcpFh, $key, $files);
      open($dcpFh, '>', $dumpCppKeys) or die('Cannot open file for dump: ',
                                             $dumpCppKeys);
      while(($key, $files) = each(%cppKeys))
      {
         print($dcpFh join(' ', $key, @$files), "\n");
      }
      print STDERR Data::Dumper->Dump([\%cppKeys], ['cppKeys'])
          if ($debug > 1);
   }
}

sub transformFilename
{
   my @transformed;
   my $stripDirname = 0;
   my @nameSubst;
   if (ref($_[0]) eq 'HASH')
   {
      my $optArgs = shift @_;
      @nameSubst = @{$optArgs->{'nameSubst'}}
          if (exists($optArgs->{'nameSubst'}));
      $stripObjDirname = $optArgs->{'stripObjDirname'}
          if (exists($optArgs->{'stripObjDirname'}));
   }
   foreach my $filename (@_)
   {
      my $fname = $filename;
      foreach my $transformRule (@nameSubst)
      {
         my ($pattern, $replacement) = ($transformRule->[0],
                                        $transformRule->[1]);
         $fname =~ s/${pattern}/${replacement}/;
      }
      (undef, undef, $fname) = File::Spec->splitpath($fname)
          if $stripObjDirname;
      push @transformed, $fname
   }
   return wantarray ? @transformed : join('', @transformed);
}

sub findRelFile($@)
{
   local $_;
   my ($file, @Paths) = @_;
   return $file if File::Spec->file_name_is_absolute($file);
   foreach my $path (@Paths)
   {
      my $qualPath = File::Spec->catfile($path, $file);
      return $qualPath if (-e $qualPath);
      print STDERR 'Requested include ', $file, ' not found in ',
          $qualPath, "\n" if $debug > 2;
   }
   return undef;
}

sub printLFEscapeLineWrap {
   local $_;
   my $options = (ref($_[0]) eq 'HASH')?shift @_:{};
   my $fd = exists($options->{'fd'})?$options->{'fd'}:\*STDOUT;
   my $linewidth = exists($options->{'linewidth'})?$options->{'linewidth'}:78;
   my $columns = $linewidth
       - exists($options->{'printed'})?$options->{'printed'}:0;
   my $lineindent = exists($options->{'lineindent'})?
       $options->{'lineindent'}:"\t";
   #
   foreach my $word (@_) {
      my $wordlength = length($word);
      if ($columns >= $wordlength + 1 + 2) {
         print $fd ' ', $word;
         $columns -= $wordlength + 1;
      } else {
         #
         # Continue onto a new line
         #
         print $fd " \\\n", $lineindent, $word;
         $columns = $linewidth - length(expand($lineindent)) - $wordlength;
      }
   }
}

sub pushUnique
{
   local $_;
   my ($listref, @elems) = @_;
   foreach my $elem (@elems)
   {
      push(@$listref, $elem) if not grep { $_ eq $elem } @$listref;
   }
}

sub haPush
{
   # insert value in list corresponding to key in hash, create new
   # list if necessary
   my ($href, $key, @values) = @_;
   if (exists($href->{$key}))
   {
      die('Must be hash of arrays!') if (ref($href->{$key}) ne 'ARRAY');
   }
   else
   {
      $href->{$key} = [];
   }
   pushUnique($href->{$key}, @values);
}

sub expand
{
   local $_;
   my @expanded = map
      { my $textcopy = $_;
        $textcopy =~ s/\t/        /; }
          @_;
   return wantarray ? @expanded : join('', @expanded);
}

BEGIN {

   my %trigraphs = ('=' => '#', '/' => '\\', "'" => '^', '(' => '[',
                    ')' => ']', '!' => '|', '<' => '{', '>' => '}', '-' => '~');
   my $trigraphsyms = quotemeta(join('', keys %trigraphs));
   my $trigraphre = qr{\?\?([$trigraphsyms])}xo;

   sub transliterateTrigraphs
   {
      local $_;
      my ($text) = @_;
      while ($text =~ s{$trigraphre}{$trigraphs{$1}})
      {
      }
      return $text;
   }

   sub validPreProcSym
   {
      return scalar ($_[0] =~ m{[a-zA-Z_]\w*});
   }

   my $operator_match = qr{(?:==
                           |!=
                           |[><]=
                           |[-+/&^%|]=
                           |(?:\|\||\&\&|>>|<<)=
                           |(?:\|\||\&\&|>>|<<)
                           |\(
                           |\)
                           |\#\#
                           |[-,+/%&|^!=><])}x;

   sub tokenize
   {
      local $_;
      my $expression = $_[0];
      my @tokens;
      if ($expression =~ m{^(.*?)(?=(["']).*?[^\\]\2)}g)
      {
         my ($prefix, $quotemark) = ($1, $2);
         my $prefixPos = pos($expression) + 1;
         $expression =~ m{\G($quotemark.*[^\\]$quotemark)(?=.*)}g;
         my ($stringOrCharConst, $stringOrCharConstEnd)
             = ($2, pos($expression));
         $expression =~ m{\G(.*)}g;
         my ($suffix, $suffixEnd) = ($3, pos($expression));
         my ($prefixTokenList, $prefixTokenPosMap) = tokenize($prefix);
         my ($suffixTokenList, $suffixTokenPosMap) = tokenize($suffix);
         @tokens = ([@$prefixTokenList, $stringOrCharConst, @$suffixTokenList],
                    [@$prefixTokenPosMap, [$prefixPos, $stringOrCharConstEnd],
                     map { [$_->[0] + $stringOrCharConstEnd + 1,
                            $_->[1] + $stringOrCharConstEnd + 1] }
                     @$suffixTokenPosMap]);
         print(STDERR Data::Dumper->Dump([\@tokens], ['tokens']), "\n")
             if ($debug > 1);
      } elsif ($expression =~ m{"}) {
         die('Unbalanced quote " in expression: ', $expression);
      } elsif ($expression ne '') {
         my (@tokenList, @tokenMappings);
         my $lastPos = -1;
         while ($expression =~ m{(.*?)
                                 (?=\s*$operator_match
                                 |\s+
                                 |$)}xgc) {
            if (defined($1) and $1 ne '')
            {
               my $tokenEndPos = pos($expression);
               push(@tokenList, $1);
               push(@tokenMappings, [$lastPos + 1, $tokenEndPos]);
               $lastPos = $tokenEndPos;
            }
            $expression =~ m/\s*?($operator_match)|\s+|$/xgc;
            if (defined($1) and $1 ne '') {
               my $tokenEndPos = pos($expression);
               push(@tokenList, $1);
               push(@tokenMappings, [$lastPos + 1, $tokenEndPos]);
               $lastPos = $tokenEndPos;
            }
         }
         @tokens = (\@tokenList, \@tokenMappings);
         print(STDERR 'Tokenized \'', $expression, '\' as ',
               join("\n", @tokenList), "\n") if $debug > 1;
      } else {
         @tokens = ([], []);
      }
      return (@tokens);
   }

}

sub parseDefinition
{
   my ($argString, $definition, $file, $line) = @_;
   my (@tokenizedDef);
   if (defined($argString))
   {
      $argString =~ s{^\s+}{};
      $argString =~ s{\s+$}{};
   }
   else { $argString = ''; }
   my @tokens = tokenize($definition);
   if (@tokens)
   {
      die(defined($file)?($file, ':', $line):('cmd arg ', $line),
          'error: \'##\' must not appear at either end or start of a macro',
          ' expansion')
          if ($tokens[0] eq '##' or $tokens[-1] eq '##');
   }
   return {
           'parameters' => [split(/\s*,\s*/, $argString)],
           'definition' => \@tokens
          };
}

sub evaluatePreProcExpression
{
   local $_;
   my ($expression, $defines, $cppKeyOut, $dontEvaluate) = @_;
   my @ast = parsePreProcExpression($expression, $defines, $cppKeyOut);
   return (defined($dontEvaluate)&&$dontEvaluate) ?
       1 : cpp_true(cpp_evaluate(@ast));
}

sub parsePreProcExpression
{
   print(STDERR 'In ', whoami(), ', line ', __LINE__, "\n") if $debug > 1;
   local $_;
   my ($expression, $defines, $cppKeyOut) = @_;
   my @tokenMapping = tokenize($expression);
   my @tokens = @{$tokenMapping[0]};
   @tokenMapping = @{$tokenMapping[1]};
   my $didSubst = 1;
   my $i;
   for ($i = 0; $i < @tokens; ++$i)
   {
      print(STDERR 'In ', whoami(), ', line ', __LINE__, "\n") if $debug > 1;
      my $token = $tokens[$i];
      if ($token eq 'defined')
      {
         # the predicate defined causes the next symbol to be
         # swallowed and evaluates to 1 or 0 depending on wether the
         # symbol is defined or not
         my ($symreflen, $symoffset);
         if ($tokens[$i + 1] eq '(')
         {
            $symreflen = 3;
            $symoffset = 2;
            die('Expected closing parenthesis, got ', $tokens[$i + 3])
                if ($tokens[$i + 3] ne ')');
         }
         else
         {
            $symreflen = 1;
            $symoffset = 1;
         }
         die('EOL in defined predicate') if ($i + $symreflen > @tokens);
         die('Invalid preprocessor symbol ', $tokens[$i + $symoffset])
             unless(isSymbol($tokens[$i + $symoffset]));
         insertDefinitionOnDemand($defines, $tokens[$i + $symoffset])
             if (!exists($defines->{$tokens[$i + $symoffset]}));
         splice(@tokens, $i, 1 + $symreflen,
                (defined($defines->{$tokens[$i + $symoffset]})?'1L':'0L'));
         next;
      }
      elsif (validPreProcSym($token))
      {
         push(@$cppKeyOut, $token) if (defined($cppKeyOut));
         insertDefinitionOnDemand($defines, $token);
         if (defined($defines->{$token}))
         {
            my @definition = @{$defines->{$token}{'definition'}};
            my @parameters = @{$defines->{$token}{'parameters'}};
            if (!@parameters)
            {
               splice(@tokens, $i, 1, @definition);
               redo;
            }
            elsif ($tokens[$i + 1] eq '(')
            {
               my @args;
               my (@argTokens);
               my $parencount = 1;
               my $j = $i + 2;
               while($j < @tokens and $parencount)
               {
                  if ($tokens[$j] eq ')')
                  {
                     last if !--$parencount;
                  }
                  elsif ($tokens[$j] eq '(')
                  {
                     ++$parencount;
                  }
                  elsif ($tokens[$j] eq ',' and $parencount == 1)
                  {
                     push(@args, [ @argTokens ]);
                     @argTokens = ();
                  }
                  push(@argTokens, $tokens[$j]);
                  ++$j;
               }
               die ('EOL in gathering macro arguments: ', @tokens[$i..$#tokens])
                   if ($parencount);
               die('Argument count mismatch: ', @parameters, ' expected, ',
                   @args, ' given.', "\n")
                   if @args != @parameters;
               my %argDefs = ( 'tokens' => map { $parameters[$_] => $args[$_]
                                              }
                               (0..$#args),
                               'tokenStream' => $expression,
                               'tokenMapping' => \@tokenMapping
                             );
               my @expandedDefinition
                   = expandMacro(\%argDefs, @tokens);
               splice(@tokens, $i, $j - $i + 1, @expandedDefinition);
               redo;
            }
         }
      }
   }
   # A12.5 macro replacement of undefined symbols
   @tokens = map { isSymbol($_)?'0L':$_ } @tokens;
   {
      print STDERR Data::Dumper->Dump([\@tokens, \@tokenMapping],
                                      ['tokens', 'tokenMapping'])
          if $debug > 1;
      my %lex = makeGetsym(@tokens);
      my @ast = conditional_expression(\%lex, 1);
      if (defined($lex{'currentsym'}()))
      {
         print(STDERR join(', ', $lex{'currentsym'}(), $lex{'rest'}()),
               "\n", Data::Dumper->Dump([\@ast], ['ast']), "\n")
             if $debug > 1;
         die('Parse of conditional incomplete: ', join($lex{'rest'}()));
      }
      print(STDERR Data::Dumper->Dump([\@ast], ['ast']))
          if $debug > 1;
      return @ast;
   }
}

sub makeGetsym
{
   my (@tokens) = @_;
   my $i = 0;
   return ('currentsym' => sub { return $i<@tokens?$tokens[$i]:undef; },
           'advancesym' => sub { return $i<@tokens?$#tokens - $i++:0; },
           'rest' => sub { return @tokens[$i..$#tokens] },
           'parse_state' => sub { return $i },
           'set_parse_state' => sub { $i = $_[0] },
           'consumed' => sub { my $state = $_[0]; return @tokens[$state..$i] });
}

sub expect
{
   my ($lex, $force, $expected) = @_;
   my $currentsym = $lex->{'currentsym'}();
   die('expect: unexpected symbol ', $currentsym,
       ' vs. expectation ', $expected)
       if ($currentsym ne $expected);
   return $lex->{'advancesym'}();
}

sub expandMacro
{
   my ($argDefs, @tokenMapping) = @_;
   print(STDERR 'In ', whoami(), ', line ', __LINE__, "\n") if $debug > 1;
   my @tokens = @{$tokenMapping[0]};
   @tokenMapping = @{$tokenMapping[1]};
   my $i;
   for ($i = 1; $i < @tokens - 1; ++$i)
   {
      if ($tokens[$i] eq '#'
          and exists($argDefs->{$tokens[$i+1]}))
      {
         splice(@tokens, $i, 2, '"' . $argDefs->{$tokens[$i+1]} . '"');
      }
      elsif ($tokens[$i] eq '##')
      {
         splice(@tokens, $i - 1, 3, @tokens[$i-1,$i+1]);
         redo;
      }
   }
   return (@tokens, @tokenMapping);
}

BEGIN {

   my @preprocCmd = ((map { split /\s+/ } '@FPP@', '@FPPFLAGS@'));

   sub preprocResult
   {
      local $_;
      my ($inputSym) = @_;
      print(STDERR 'In ', whoami(), ', line ', __LINE__, "\n") if $debug > 1;
      my ($tempFileFh, $tempFileName)
          = File::Temp::tempfile('SUFFIX' => '.f90');
      print($tempFileFh $inputSym, "\n")
          or die('Write to temporary file ', $tempFileName, ' failed!');
      close($tempFileFh)
          or die('Close of temporary file ', $tempFileName, ' failed!');
      my $preprocOutputFh;
      open($preprocOutputFh, join(' ', @preprocCmd, $tempFileName, '|'))
          or die('Open of pipe to preprocessor failed!');
      my $preprocOutput = '';
      my $p = '';
      while (<$preprocOutputFh>)
      {
         $p .= $_;
         $preprocOutput .= $_ unless (m{^#});
      }
      chomp($preprocOutput);
      close($preprocOutputFh)
          or die('Close of pipe to preprocessor failed!');
      print(STDERR $tempFileName, "\n", $p, "\n")
          if $debug > 2;
      system("cat $tempFileName >&2")
          if $debug > 2;
      unlink($tempFileName)
          or die('Unlinking temporary file ', $tempFileName, ' failed!');
      print(STDERR "symbol '", $inputSym, "' replaced with '",
            $preprocOutput, "'\n") if $debug > 2;
      return $preprocOutput eq $inputSym ? undef : $preprocOutput;
   }

   sub insertDefinitionOnDemand
   {
      my ($defines, $token) = @_;
      print(STDERR 'In ', whoami(), ', line ', __LINE__, "\n") if $debug > 1;
      if (exists($defines->{$token}))
      {
         return $defines->{$token};
      }
      else
      {
         my $definition = preprocResult($token);
         if (defined($definition))
         {
            $defines{$token} = $defines->{$token}
                    = parseDefinition(undef, $definition, '', '');
         }
         else
         {
            $defines{$token} = $defines->{$token} = undef;
         }
      }
   }

   sub parse_backoff
   {
      my ($lex, $save, $force, @msg) = @_;
      $lex->{'set_parse_state'}($save);
      if ($force)
      {
         die(@msg);
      }
      else
      {
         return ();
      }
   }

   my %evaluations;

   sub expression
   {
      local $_;
      my ($lex, $force) = @_;
      my $save = $lex->{'parse_state'}();
      print(STDERR 'In ', whoami(), ', left over: ',
            join(', ', $lex->{'rest'}()), "\n")
          if $debug > 1;
      my @expression = ('expression');
      my @assignment_expression = assignment_expression($lex, $force);
      if (@assignment_expression
          and (!defined($_ = $lex->{'currentsym'}())
               or $_ ne ','))
      {
         return @assignment_expression;
      }
      else
      {
         my @sub_expression = @assignment_expression
             ? @assignment_expression : expression($lex, $force);
         my $currentsym;
         if (@sub_expression
             and defined ($currentsym = $lex->{'currentsym'}())
             and $currentsym eq ','
             and $lex->{'advancesym'}())
         {
            print(STDERR 'In ', whoami(), ', line ', __LINE__, ', left over: ',
                  join(', ', $lex->{'rest'}()), "\n") if $debug > 1;
            if (@assignment_expression = assignment_expression($lex, $force))
            {
               return ('expression', \@sub_expression, \@assignment_expression);
            }
         }
      }
   }

   my @assignment_operators = ('=', '*=', '/=', '%=', '+=', '-=',
                               '<<=', '>>=', '&=', '^=', '|=');

   sub assignment_expression
   {
      local $_;
      my ($lex, $force) = @_;
      my $save = $lex->{'parse_state'}();
      print(STDERR 'In ', whoami(), ', left over: ',
            join(', ', $lex->{'rest'}()), "\n")
          if $debug > 1;
      my @conditional_expression = conditional_expression($lex, $force);
      if (@conditional_expression)
      {
         return @conditional_expression;
      }
      else
      {
         my @unary_expression = unary_expression($lex, $force);
         my ($currentsym, @assignment_expression);
         if (@unary_expression
             and defined ($currentsym = $lex->{'getcurrentsym'}())
             and (grep { $currentsym eq $_ } @assignment_operators)
             and $lex->{'advancesym'}()
             and (@assignment_expression = assignment_expression($lex,$force)))
         {
            print(STDERR 'In ', whoami(), ', line ', __LINE__, ', left over: ',
                  join(', ', $lex->{'rest'}()), "\n") if $debug > 1;
            return ('assignment_expression', $currentsym,
                    \@unary_expression, \@assignment_expression);
         }
      }
   }

   $evaluations{'conditional_expression'}
       = sub { return cpp_true(cpp_evaluate(@{$_[0]}))
                   ? (cpp_evaluate(@{$_[1]}))
                       : (cpp_evaluate(@{$_[2]})); };

   sub conditional_expression
   {
      local $_;
      my ($lex, $force) = @_;
      my $save = $lex->{'parse_state'}();
      print(STDERR 'In ', whoami(), ', left over: ',
            join(', ', $lex->{'rest'}()), "\n")
          if $debug > 1;
      my @logical_or_expression
          = logical_or_expression($lex, $force);
      my $currentsym;
      if (defined($currentsym = $lex->{'currentsym'}())
          and $currentsym eq '?')
      {
         my @elseexpression;
         my @ifexpression;
         if ($lex->{'advancesym'}()
             and (@ifexpression = expression($lex, $force))
             and defined($currentsym = $lex->{'currentsym'}())
             and $currentsym eq ':'
             and $lex->{'advancesym'}()
             and (@elseexpression = conditional_expression($lex, $force)))
         {
            return ('conditional_expression', @logical_or_expression,
                    @ifexpression, @elseexpression);
         }
         else
         {
            return parse_backoff($lex, $save, $force,
                                 'ternary operator \':\' not' .
                                 ' followed by else expression!');
         }
      }
      return @logical_or_expression;
   }

   $evaluations{'logical_or_expression'}
       = sub { my $accum = 0;
               foreach my $subexpression (@_) {
                  if (cpp_true(cpp_evaluate(@$subexpression))) {
                     $accum = 1;
                     last;
                  }
               }
               return ('constant', 'int', $accum);
            };

   sub logical_or_expression
   {
      local $_;
      my ($lex, $force) = @_;
      my $save = $lex->{'parse_state'}();
      print(STDERR 'In ', whoami(), ', left over: ',
            join(', ', $lex->{'rest'}()), "\n")
          if $debug > 1;
      my @logical_and_expression
          = logical_and_expression($lex, 0);
      if (@logical_and_expression
          and (!defined($lex->{'currentsym'}())
               or $lex->{'currentsym'}() ne '||'))
      {
         return @logical_and_expression;
      }
      elsif (@logical_and_expression)
      {
         my @logical_or_expression = ('logical_or_expression',
                                      [ @logical_and_expression ]);
         my $currentsym;
         while (defined($currentsym = $lex->{'currentsym'}())
                and $lex->{'currentsym'}() eq '||'
                and $lex->{'advancesym'}())
         {
            print(STDERR 'In ', whoami(), ', left over: ',
                  join(', ', $lex->{'rest'}()), "\n") if $debug > 1;
            if (@logical_and_expression = logical_and_expression($lex, $force))
            {
               push(@logical_or_expression, [ @logical_and_expression ]);
            }
            else
            {
               return parse_backoff($lex, $save, $force,
                                    'Invalid logical_or_expression ',
                                    $lex->{'consumed'}($save));
            }
         }
         return @logical_or_expression;
      }
      return parse_backoff($lex, $save, $force,
                           'Invalid logical_or_expression ',
                           $lex->{'consumed'}($save));
   }

   $evaluations{'logical_and_expression'}
       = sub { my $accum = 1;
               foreach my $subexpression (@_) {
                  print(STDERR 'In ', whoami(), ', result: ',
                        cpp_true(cpp_evaluate(@$subexpression)),
                        "\n") if $debug > 1;
                  if (!cpp_true(cpp_evaluate(@$subexpression))) {
                     $accum = 0;
                     last;
                  }
               }
               return ('constant', 'int', $accum);
            };

   sub logical_and_expression
   {
      local $_;
      my ($lex, $force) = @_;
      my $save = $lex->{'parse_state'}();
      print(STDERR 'In ', whoami(), ', left over: ',
            join(', ', $lex->{'rest'}()), "\n")
          if $debug > 1;
      my @inclusive_or_expression
          = inclusive_or_expression($lex, 0);
      if (@inclusive_or_expression
          and (!defined($lex->{'currentsym'}())
               or $lex->{'currentsym'}() ne '&&'))
      {
         return @inclusive_or_expression;
      }
      elsif (@inclusive_or_expression)
      {
         my @logical_and_expression = ('logical_and_expression',
                                       [ @inclusive_or_expression ]);
         my $currentsym;
         while (defined($currentsym = $lex->{'currentsym'}())
                and $currentsym eq '&&'
                and $lex->{'advancesym'}())
         {
            print(STDERR 'In ', whoami(), ', left over: ',
                  join(', ', $lex->{'rest'}()), "\n") if $debug > 1;
            if (@inclusive_or_expression
                = inclusive_or_expression($lex, $force))
            {
               push(@logical_and_expression, [ @inclusive_or_expression ] );
            }
            else
            {
               return parse_backoff($lex, $save, $force,
                                    'Invalid logical_and_expression ',
                                    $lex->{'consumed'}($save));
            }
         }
         return @logical_and_expression;
      }
      return parse_backoff($lex, $save, $force,
For faster browsing, not all history is shown. View entire blame