cmDependsFortran.cxx 24.3 KB
Newer Older
1
2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
3
4
#include "cmDependsFortran.h"

5
#include <assert.h>
6
#include <cmsys/FStream.hxx>
7
8
9
10
11
#include <iostream>
#include <map>
#include <stdlib.h>
#include <string.h>
#include <utility>
12

13
14
15
16
17
18
19
20
21
#include "cmFortranParser.h" /* Interface to parser object.  */
#include "cmGeneratedFileStream.h"
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
#include "cmOutputConverter.h"
#include "cmStateDirectory.h"
#include "cmStateSnapshot.h"
#include "cmSystemTools.h"

22
23
24
25
// TODO: Test compiler for the case of the mod file.  Some always
// use lower case and some always use upper case.  I do not know if any
// use the case from the source code.

26
27
28
29
class cmDependsFortranInternals
{
public:
  // The set of modules provided by this target.
30
  std::set<std::string> TargetProvides;
31
32

  // Map modules required by this target to locations.
33
  typedef std::map<std::string, std::string> TargetRequiresMap;
34
35
36
  TargetRequiresMap TargetRequires;

  // Information about each object file.
37
  typedef std::map<std::string, cmFortranSourceInfo> ObjectInfoMap;
38
39
  ObjectInfoMap ObjectInfo;

40
41
  cmFortranSourceInfo& CreateObjectInfo(const char* obj, const char* src)
  {
42
    std::map<std::string, cmFortranSourceInfo>::iterator i =
43
      this->ObjectInfo.find(obj);
44
45
46
    if (i == this->ObjectInfo.end()) {
      std::map<std::string, cmFortranSourceInfo>::value_type entry(
        obj, cmFortranSourceInfo());
47
48
49
      i = this->ObjectInfo.insert(entry).first;
      i->second.Source = src;
    }
50
51
    return i->second;
  }
52
53
};

54
cmDependsFortran::cmDependsFortran()
Daniel Pfeifer's avatar
Daniel Pfeifer committed
55
  : Internal(CM_NULLPTR)
56
57
58
{
}

59
60
61
cmDependsFortran::cmDependsFortran(cmLocalGenerator* lg)
  : cmDepends(lg)
  , Internal(new cmDependsFortranInternals)
62
{
63
64
65
  // Configure the include file search path.
  this->SetIncludePathFromLanguage("Fortran");

66
67
68
  // Get the list of definitions.
  std::vector<std::string> definitions;
  cmMakefile* mf = this->LocalGenerator->GetMakefile();
69
70
  if (const char* c_defines =
        mf->GetDefinition("CMAKE_TARGET_DEFINITIONS_Fortran")) {
71
    cmSystemTools::ExpandListArgument(c_defines, definitions);
72
  }
73

74
  // translate i.e. FOO=BAR to FOO and add it to the list of defined
75
  // preprocessor symbols
76
77
  for (std::vector<std::string>::const_iterator it = definitions.begin();
       it != definitions.end(); ++it) {
78
    std::string def = *it;
79
    std::string::size_type assignment = def.find('=');
80
    if (assignment != std::string::npos) {
81
      def = it->substr(0, assignment);
82
    }
83
84
    this->PPDefinitions.insert(def);
  }
85
86
87
88
}

cmDependsFortran::~cmDependsFortran()
{
89
  delete this->Internal;
90
91
}

92
bool cmDependsFortran::WriteDependencies(const std::set<std::string>& sources,
93
94
95
                                         const std::string& obj,
                                         std::ostream& /*makeDepends*/,
                                         std::ostream& /*internalDepends*/)
96
97
{
  // Make sure this is a scanning instance.
98
  if (sources.empty() || sources.begin()->empty()) {
99
    cmSystemTools::Error("Cannot scan dependencies without a source file.");
100
    return false;
101
102
  }
  if (obj.empty()) {
103
104
    cmSystemTools::Error("Cannot scan dependencies without an object file.");
    return false;
105
  }
106

107
  bool okay = true;
108
109
  for (std::set<std::string>::const_iterator it = sources.begin();
       it != sources.end(); ++it) {
110
111
    const std::string& src = *it;
    // Get the information object for this source.
112
    cmFortranSourceInfo& info =
113
      this->Internal->CreateObjectInfo(obj.c_str(), src.c_str());
114

115
116
117
    // Create the parser object. The constructor takes info by reference,
    // so we may look into the resulting objects later.
    cmFortranParser parser(this->IncludePath, this->PPDefinitions, info);
118

119
    // Push on the starting file.
120
    cmFortranParser_FilePush(&parser, src.c_str());
121

122
    // Parse the translation unit.
123
    if (cmFortran_yyparse(parser.Scanner) != 0) {
124
125
      // Failed to parse the file.  Report failure to write dependencies.
      okay = false;
126
127
128
129
130
131
      /* clang-format off */
      std::cerr <<
        "warning: failed to parse dependencies from Fortran source "
        "'" << src << "': " << parser.Error << std::endl
        ;
      /* clang-format on */
132
    }
133
  }
134
  return okay;
135
136
137
138
139
140
141
142
}

bool cmDependsFortran::Finalize(std::ostream& makeDepends,
                                std::ostream& internalDepends)
{
  // Prepare the module search process.
  this->LocateModules();

143
  // Get the directory in which stamp files will be stored.
144
  const char* stamp_dir = this->TargetDirectory.c_str();
145
146
147

  // Get the directory in which module files will be created.
  cmMakefile* mf = this->LocalGenerator->GetMakefile();
148
149
  std::string mod_dir =
    mf->GetSafeDefinition("CMAKE_Fortran_TARGET_MODULE_DIR");
150
151
152
  if (mod_dir.empty()) {
    mod_dir = this->LocalGenerator->GetCurrentBinaryDirectory();
  }
153

154
155
156
  // Actually write dependencies to the streams.
  typedef cmDependsFortranInternals::ObjectInfoMap ObjectInfoMap;
  ObjectInfoMap const& objInfo = this->Internal->ObjectInfo;
157
158
159
160
161
  for (ObjectInfoMap::const_iterator i = objInfo.begin(); i != objInfo.end();
       ++i) {
    if (!this->WriteDependenciesReal(i->first.c_str(), i->second, mod_dir,
                                     stamp_dir, makeDepends,
                                     internalDepends)) {
162
163
      return false;
    }
164
  }
165
166
167
168
169
170
171

  // Store the list of modules provided by this target.
  std::string fiName = this->TargetDirectory;
  fiName += "/fortran.internal";
  cmGeneratedFileStream fiStream(fiName.c_str());
  fiStream << "# The fortran modules provided by this target.\n";
  fiStream << "provides\n";
172
  std::set<std::string> const& provides = this->Internal->TargetProvides;
173
174
  for (std::set<std::string>::const_iterator i = provides.begin();
       i != provides.end(); ++i) {
175
    fiStream << " " << *i << "\n";
176
  }
177
178

  // Create a script to clean the modules.
179
  if (!provides.empty()) {
180
181
182
183
    std::string fcName = this->TargetDirectory;
    fcName += "/cmake_clean_Fortran.cmake";
    cmGeneratedFileStream fcStream(fcName.c_str());
    fcStream << "# Remove fortran modules provided by this target.\n";
184
    fcStream << "FILE(REMOVE";
185
186
    std::string currentBinDir =
      this->LocalGenerator->GetCurrentBinaryDirectory();
187
188
    for (std::set<std::string>::const_iterator i = provides.begin();
         i != provides.end(); ++i) {
189
190
191
192
193
194
195
196
197
198
199
200
201
      std::string mod_upper = mod_dir;
      mod_upper += "/";
      mod_upper += cmSystemTools::UpperCase(*i);
      mod_upper += ".mod";
      std::string mod_lower = mod_dir;
      mod_lower += "/";
      mod_lower += *i;
      mod_lower += ".mod";
      std::string stamp = stamp_dir;
      stamp += "/";
      stamp += *i;
      stamp += ".mod.stamp";
      fcStream << "\n";
202
      fcStream << "  \""
203
               << this->MaybeConvertToRelativePath(currentBinDir, mod_lower)
204
               << "\"\n";
205
      fcStream << "  \""
206
               << this->MaybeConvertToRelativePath(currentBinDir, mod_upper)
207
               << "\"\n";
208
      fcStream << "  \""
209
               << this->MaybeConvertToRelativePath(currentBinDir, stamp)
210
               << "\"\n";
211
    }
212
213
    fcStream << "  )\n";
  }
214
215
216
217
218
219
220
221
  return true;
}

void cmDependsFortran::LocateModules()
{
  // Collect the set of modules provided and required by all sources.
  typedef cmDependsFortranInternals::ObjectInfoMap ObjectInfoMap;
  ObjectInfoMap const& objInfo = this->Internal->ObjectInfo;
222
223
  for (ObjectInfoMap::const_iterator infoI = objInfo.begin();
       infoI != objInfo.end(); ++infoI) {
224
    cmFortranSourceInfo const& info = infoI->second;
225
226
227
    // Include this module in the set provided by this target.
    this->Internal->TargetProvides.insert(info.Provides.begin(),
                                          info.Provides.end());
228

229
230
    for (std::set<std::string>::const_iterator i = info.Requires.begin();
         i != info.Requires.end(); ++i) {
231
232
      this->Internal->TargetRequires[*i] = "";
    }
233
  }
234
235

  // Short-circuit for simple targets.
236
  if (this->Internal->TargetRequires.empty()) {
237
    return;
238
  }
239
240
241
242
243
244
245

  // Match modules provided by this target to those it requires.
  this->MatchLocalModules();

  // Load information about other targets.
  cmMakefile* mf = this->LocalGenerator->GetMakefile();
  std::vector<std::string> infoFiles;
246
247
  if (const char* infoFilesValue =
        mf->GetDefinition("CMAKE_TARGET_LINKED_INFO_FILES")) {
248
    cmSystemTools::ExpandListArgument(infoFilesValue, infoFiles);
249
250
251
  }
  for (std::vector<std::string>::const_iterator i = infoFiles.begin();
       i != infoFiles.end(); ++i) {
252
253
    std::string targetDir = cmSystemTools::GetFilenamePath(*i);
    std::string fname = targetDir + "/fortran.internal";
254
    cmsys::ifstream fin(fname.c_str());
255
    if (fin) {
256
      this->MatchRemoteModules(fin, targetDir.c_str());
257
    }
258
  }
259
260
261
262
}

void cmDependsFortran::MatchLocalModules()
{
263
  const char* stampDir = this->TargetDirectory.c_str();
264
  std::set<std::string> const& provides = this->Internal->TargetProvides;
265
266
  for (std::set<std::string>::const_iterator i = provides.begin();
       i != provides.end(); ++i) {
267
    this->ConsiderModule(i->c_str(), stampDir);
268
  }
269
270
271
}

void cmDependsFortran::MatchRemoteModules(std::istream& fin,
272
                                          const char* stampDir)
273
274
{
  std::string line;
275
  bool doing_provides = false;
276
  while (cmSystemTools::GetLineFromStream(fin, line)) {
277
    // Ignore comments and empty lines.
278
    if (line.empty() || line[0] == '#' || line[0] == '\r') {
279
      continue;
280
    }
281

282
283
284
    if (line[0] == ' ') {
      if (doing_provides) {
        this->ConsiderModule(line.c_str() + 1, stampDir);
285
      }
286
    } else if (line == "provides") {
287
      doing_provides = true;
288
    } else {
289
290
      doing_provides = false;
    }
291
  }
292
293
}

294
void cmDependsFortran::ConsiderModule(const char* name, const char* stampDir)
295
296
297
298
299
{
  // Locate each required module.
  typedef cmDependsFortranInternals::TargetRequiresMap TargetRequiresMap;
  TargetRequiresMap::iterator required =
    this->Internal->TargetRequires.find(name);
300
301
  if (required != this->Internal->TargetRequires.end() &&
      required->second.empty()) {
302
    // The module is provided by a CMake target.  It will have a stamp file.
303
    std::string stampFile = stampDir;
304
305
306
307
    stampFile += "/";
    stampFile += name;
    stampFile += ".mod.stamp";
    required->second = stampFile;
308
  }
309
310
}

311
312
313
314
315
316
bool cmDependsFortran::WriteDependenciesReal(const char* obj,
                                             cmFortranSourceInfo const& info,
                                             std::string const& mod_dir,
                                             const char* stamp_dir,
                                             std::ostream& makeDepends,
                                             std::ostream& internalDepends)
317
318
319
320
321
322
{
  typedef cmDependsFortranInternals::TargetRequiresMap TargetRequiresMap;

  // Get the source file for this object.
  const char* src = info.Source.c_str();

323
  // Write the include dependencies to the output stream.
324
  std::string binDir = this->LocalGenerator->GetBinaryDirectory();
325
  std::string obj_i = this->MaybeConvertToRelativePath(binDir, obj);
326
  std::string obj_m = cmSystemTools::ConvertToOutputPath(obj_i.c_str());
327
  internalDepends << obj_i << std::endl;
328
  internalDepends << " " << src << std::endl;
329
330
  for (std::set<std::string>::const_iterator i = info.Includes.begin();
       i != info.Includes.end(); ++i) {
331
332
333
334
    makeDepends << obj_m << ": "
                << cmSystemTools::ConvertToOutputPath(
                     this->MaybeConvertToRelativePath(binDir, *i).c_str())
                << std::endl;
335
    internalDepends << " " << *i << std::endl;
336
  }
337
  makeDepends << std::endl;
338

339
  // Write module requirements to the output stream.
340
341
  for (std::set<std::string>::const_iterator i = info.Requires.begin();
       i != info.Requires.end(); ++i) {
342
    // Require only modules not provided in the same source.
343
344
    if (std::set<std::string>::const_iterator(info.Provides.find(*i)) !=
        info.Provides.end()) {
345
      continue;
346
    }
347
348
349

    // If the module is provided in this target special handling is
    // needed.
350
351
    if (this->Internal->TargetProvides.find(*i) !=
        this->Internal->TargetProvides.end()) {
352
353
354
      // The module is provided by a different source in the same
      // target.  Add the proxy dependency to make sure the other
      // source builds first.
355
      std::string proxy = stamp_dir;
356
357
358
      proxy += "/";
      proxy += *i;
      proxy += ".mod.proxy";
359
      proxy = cmSystemTools::ConvertToOutputPath(
360
        this->MaybeConvertToRelativePath(binDir, proxy).c_str());
361

362
      // since we require some things add them to our list of requirements
363
      makeDepends << obj_m << ".requires: " << proxy << std::endl;
364
    }
365

366
367
368
369
    // The object file should depend on timestamped files for the
    // modules it uses.
    TargetRequiresMap::const_iterator required =
      this->Internal->TargetRequires.find(*i);
370
371
372
373
    if (required == this->Internal->TargetRequires.end()) {
      abort();
    }
    if (!required->second.empty()) {
374
      // This module is known.  Depend on its timestamp file.
375
      std::string stampFile = cmSystemTools::ConvertToOutputPath(
376
        this->MaybeConvertToRelativePath(binDir, required->second).c_str());
377
      makeDepends << obj_m << ": " << stampFile << "\n";
378
    } else {
379
380
381
      // This module is not known to CMake.  Try to locate it where
      // the compiler will and depend on that.
      std::string module;
382
      if (this->FindModule(*i, module)) {
383
        module = cmSystemTools::ConvertToOutputPath(
384
          this->MaybeConvertToRelativePath(binDir, module).c_str());
385
        makeDepends << obj_m << ": " << module << "\n";
386
387
      }
    }
388
  }
389
390

  // Write provided modules to the output stream.
391
392
  for (std::set<std::string>::const_iterator i = info.Provides.begin();
       i != info.Provides.end(); ++i) {
393
    std::string proxy = stamp_dir;
394
395
396
    proxy += "/";
    proxy += *i;
    proxy += ".mod.proxy";
397
    proxy = cmSystemTools::ConvertToOutputPath(
398
      this->MaybeConvertToRelativePath(binDir, proxy).c_str());
399
    makeDepends << proxy << ": " << obj_m << ".provides" << std::endl;
400
  }
401

402
  // If any modules are provided then they must be converted to stamp files.
403
  if (!info.Provides.empty()) {
404
405
    // Create a target to copy the module after the object file
    // changes.
406
    makeDepends << obj_m << ".provides.build:\n";
407
408
    for (std::set<std::string>::const_iterator i = info.Provides.begin();
         i != info.Provides.end(); ++i) {
409
410
411
      // Include this module in the set provided by this target.
      this->Internal->TargetProvides.insert(*i);

412
413
414
      // Always use lower case for the mod stamp file name.  The
      // cmake_copy_f90_mod will call back to this class, which will
      // try various cases for the real mod file name.
415
      std::string m = cmSystemTools::LowerCase(*i);
416
417
418
      std::string modFile = mod_dir;
      modFile += "/";
      modFile += *i;
419
      modFile = this->LocalGenerator->ConvertToOutputFormat(
420
        this->MaybeConvertToRelativePath(binDir, modFile),
421
        cmOutputConverter::SHELL);
422
      std::string stampFile = stamp_dir;
423
424
425
      stampFile += "/";
      stampFile += m;
      stampFile += ".mod.stamp";
426
      stampFile = this->LocalGenerator->ConvertToOutputFormat(
427
        this->MaybeConvertToRelativePath(binDir, stampFile),
428
        cmOutputConverter::SHELL);
429
430
      makeDepends << "\t$(CMAKE_COMMAND) -E cmake_copy_f90_mod " << modFile
                  << " " << stampFile;
431
432
      cmMakefile* mf = this->LocalGenerator->GetMakefile();
      const char* cid = mf->GetDefinition("CMAKE_Fortran_COMPILER_ID");
433
      if (cid && *cid) {
434
        makeDepends << " " << cid;
435
      }
436
437
      makeDepends << "\n";
    }
438
439
    // After copying the modules update the timestamp file so that
    // copying will not be done again until the source rebuilds.
440
    makeDepends << "\t$(CMAKE_COMMAND) -E touch " << obj_m
Bill Hoffman's avatar
Bill Hoffman committed
441
                << ".provides.build\n";
442
443
444

    // Make sure the module timestamp rule is evaluated by the time
    // the target finishes building.
445
446
    std::string driver = this->TargetDirectory;
    driver += "/build";
447
    driver = cmSystemTools::ConvertToOutputPath(
448
      this->MaybeConvertToRelativePath(binDir, driver).c_str());
449
    makeDepends << driver << ": " << obj_m << ".provides.build\n";
450
  }
451

452
453
454
  return true;
}

455
bool cmDependsFortran::FindModule(std::string const& name, std::string& module)
456
457
458
459
460
461
462
463
464
{
  // Construct possible names for the module file.
  std::string mod_upper = cmSystemTools::UpperCase(name);
  std::string mod_lower = name;
  mod_upper += ".mod";
  mod_lower += ".mod";

  // Search the include path for the module.
  std::string fullName;
465
466
  for (std::vector<std::string>::const_iterator i = this->IncludePath.begin();
       i != this->IncludePath.end(); ++i) {
467
468
469
470
    // Try the lower-case name.
    fullName = *i;
    fullName += "/";
    fullName += mod_lower;
471
    if (cmSystemTools::FileExists(fullName.c_str(), true)) {
472
473
      module = fullName;
      return true;
474
    }
475
476
477
478
479

    // Try the upper-case name.
    fullName = *i;
    fullName += "/";
    fullName += mod_upper;
480
    if (cmSystemTools::FileExists(fullName.c_str(), true)) {
481
482
483
      module = fullName;
      return true;
    }
484
  }
485
486
487
  return false;
}

488
489
490
491
492
bool cmDependsFortran::CopyModule(const std::vector<std::string>& args)
{
  // Implements
  //
  //   $(CMAKE_COMMAND) -E cmake_copy_f90_mod input.mod output.mod.stamp
493
  //                                          [compiler-id]
494
495
496
497
498
499
500
501
  //
  // Note that the case of the .mod file depends on the compiler.  In
  // the future this copy could also account for the fact that some
  // compilers include a timestamp in the .mod file so it changes even
  // when the interface described in the module does not.

  std::string mod = args[2];
  std::string stamp = args[3];
502
  std::string compilerId;
503
  if (args.size() >= 5) {
504
    compilerId = args[4];
505
  }
506
  std::string mod_dir = cmSystemTools::GetFilenamePath(mod);
507
508
509
  if (!mod_dir.empty()) {
    mod_dir += "/";
  }
510
511
512
513
  std::string mod_upper = mod_dir;
  mod_upper += cmSystemTools::UpperCase(cmSystemTools::GetFilenameName(mod));
  std::string mod_lower = mod_dir;
  mod_lower += cmSystemTools::LowerCase(cmSystemTools::GetFilenameName(mod));
514
515
516
  mod += ".mod";
  mod_upper += ".mod";
  mod_lower += ".mod";
517
518
519
520
521
522
  if (cmSystemTools::FileExists(mod_upper.c_str(), true)) {
    if (cmDependsFortran::ModulesDiffer(mod_upper.c_str(), stamp.c_str(),
                                        compilerId.c_str())) {
      if (!cmSystemTools::CopyFileAlways(mod_upper, stamp)) {
        std::cerr << "Error copying Fortran module from \"" << mod_upper
                  << "\" to \"" << stamp << "\".\n";
523
        return false;
524
525
      }
    }
526
    return true;
527
528
  }
  if (cmSystemTools::FileExists(mod_lower.c_str(), true)) {
529
530
531
532
533
    if (cmDependsFortran::ModulesDiffer(mod_lower.c_str(), stamp.c_str(),
                                        compilerId.c_str())) {
      if (!cmSystemTools::CopyFileAlways(mod_lower, stamp)) {
        std::cerr << "Error copying Fortran module from \"" << mod_lower
                  << "\" to \"" << stamp << "\".\n";
534
        return false;
535
536
      }
    }
537
538
    return true;
  }
539

540
541
  std::cerr << "Error copying Fortran module \"" << args[2] << "\".  Tried \""
            << mod_upper << "\" and \"" << mod_lower << "\".\n";
542
543
544
  return false;
}

545
546
547
// Helper function to look for a short sequence in a stream.  If this
// is later used for longer sequences it should be re-written using an
// efficient string search algorithm such as Boyer-Moore.
548
549
static bool cmFortranStreamContainsSequence(std::istream& ifs, const char* seq,
                                            int len)
550
551
552
553
{
  assert(len > 0);

  int cur = 0;
554
  while (cur < len) {
555
556
    // Get the next character.
    int token = ifs.get();
557
    if (!ifs) {
558
      return false;
559
    }
560
561

    // Check the character.
562
    if (token == static_cast<int>(seq[cur])) {
563
      ++cur;
564
    } else {
565
566
567
      // Assume the sequence has no repeating subsequence.
      cur = 0;
    }
568
  }
569
570
571
572
573
574

  // The entire sequence was matched.
  return true;
}

// Helper function to compare the remaining content in two streams.
575
static bool cmFortranStreamsDiffer(std::istream& ifs1, std::istream& ifs2)
576
577
{
  // Compare the remaining content.
578
  for (;;) {
579
580
    int ifs1_c = ifs1.get();
    int ifs2_c = ifs2.get();
581
    if (!ifs1 && !ifs2) {
582
583
584
      // We have reached the end of both streams simultaneously.
      // The streams are identical.
      return false;
585
    }
586

587
    if (!ifs1 || !ifs2 || ifs1_c != ifs2_c) {
588
589
590
591
      // We have reached the end of one stream before the other or
      // found differing content.  The streams are different.
      break;
    }
592
  }
593
594
595
596

  return true;
}

597
bool cmDependsFortran::ModulesDiffer(const char* modFile,
598
599
                                     const char* stampFile,
                                     const char* compilerId)
600
601
{
  /*
602
603
604
605
606
  gnu >= 4.9:
    A mod file is an ascii file compressed with gzip.
    Compiling twice produces identical modules.

  gnu < 4.9:
607
608
609
610
611
612
613
614
615
616
617
    A mod file is an ascii file.
    <bar.mod>
    FORTRAN module created from /path/to/foo.f90 on Sun Dec 30 22:47:58 2007
    If you edit this, you'll get what you deserve.
    ...
    </bar.mod>
    As you can see the first line contains the date.

  intel:
    A mod file is a binary file.
    However, looking into both generated bar.mod files with a hex editor
618
619
620
    shows that they differ only before a sequence linefeed-zero (0x0A 0x00)
    which is located some bytes in front of the absoulte path to the source
    file.
621
622

  sun:
623
    A mod file is a binary file.  Compiling twice produces identical modules.
624
625

  others:
626
    TODO ...
627
  */
628
629
630
631
632

  /* Compilers which do _not_ produce different mod content when the same
   * source is compiled twice
   *   -SunPro
   */
633
  if (strcmp(compilerId, "SunPro") == 0) {
634
    return cmSystemTools::FilesDiffer(modFile, stampFile);
635
  }
636

637
#if defined(_WIN32) || defined(__CYGWIN__)
638
639
  cmsys::ifstream finModFile(modFile, std::ios::in | std::ios::binary);
  cmsys::ifstream finStampFile(stampFile, std::ios::in | std::ios::binary);
640
#else
641
642
  cmsys::ifstream finModFile(modFile);
  cmsys::ifstream finStampFile(stampFile);
643
#endif
644
  if (!finModFile || !finStampFile) {
645
646
    // At least one of the files does not exist.  The modules differ.
    return true;
647
  }
648

649
650
651
652
653
  /* Compilers which _do_ produce different mod content when the same
   * source is compiled twice
   *   -GNU
   *   -Intel
   *
654
655
   * Eat the stream content until all recompile only related changes
   * are left behind.
656
   */
657
  if (strcmp(compilerId, "GNU") == 0) {
658
659
660
661
    // GNU Fortran 4.9 and later compress .mod files with gzip
    // but also do not include a date so we can fall through to
    // compare them without skipping any prefix.
    unsigned char hdr[2];
Daniel Pfeifer's avatar
Daniel Pfeifer committed
662
    bool okay = !finModFile.read(reinterpret_cast<char*>(hdr), 2).fail();
663
    finModFile.seekg(0);
Daniel Pfeifer's avatar
Daniel Pfeifer committed
664
    if (!okay || hdr[0] != 0x1f || hdr[1] != 0x8b) {
665
      const char seq[1] = { '\n' };
666
      const int seqlen = 1;
667

668
      if (!cmFortranStreamContainsSequence(finModFile, seq, seqlen)) {
669
670
671
672
        // The module is of unexpected format.  Assume it is different.
        std::cerr << compilerId << " fortran module " << modFile
                  << " has unexpected format." << std::endl;
        return true;
673
      }
674

675
      if (!cmFortranStreamContainsSequence(finStampFile, seq, seqlen)) {
676
677
        // The stamp must differ if the sequence is not contained.
        return true;
678
      }
679
    }
680
681
  } else if (strcmp(compilerId, "Intel") == 0) {
    const char seq[2] = { '\n', '\0' };
682
    const int seqlen = 2;
683

684
685
686
687
688
689
    // Skip the leading byte which appears to be a version number.
    // We do not need to check for an error because the sequence search
    // below will fail in that case.
    finModFile.get();
    finStampFile.get();

690
    if (!cmFortranStreamContainsSequence(finModFile, seq, seqlen)) {
691
692
693
694
      // The module is of unexpected format.  Assume it is different.
      std::cerr << compilerId << " fortran module " << modFile
                << " has unexpected format." << std::endl;
      return true;
695
    }
696

697
    if (!cmFortranStreamContainsSequence(finStampFile, seq, seqlen)) {
698
699
      // The stamp must differ if the sequence is not contained.
      return true;
700
    }
701
  }
702

703
  // Compare the remaining content.  If no compiler id matched above,
704
705
  // including the case none was given, this will compare the whole
  // content.
706
  return cmFortranStreamsDiffer(finModFile, finStampFile);
707
}
708
709
710
711

std::string cmDependsFortran::MaybeConvertToRelativePath(
  std::string const& base, std::string const& path)
{
712
713
714
715
716
  if (!cmOutputConverter::ContainedInDirectory(
        base, path, this->LocalGenerator->GetStateSnapshot().GetDirectory())) {
    return path;
  }
  return cmOutputConverter::ForceToRelativePath(base, path);
717
}