cmDependsFortran.cxx 24.2 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 "cmFortranParser.h" /* Interface to parser object.  */
6
#include "cmGeneratedFileStream.h"
7 8
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
9
#include "cmOutputConverter.h"
10
#include "cmSystemTools.h"
11

12
#include <assert.h>
13
#include <cmsys/FStream.hxx>
14 15 16 17 18
#include <iostream>
#include <map>
#include <stdlib.h>
#include <string.h>
#include <utility>
19

20 21 22 23
// 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.

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

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

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

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

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

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

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

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

cmDependsFortran::~cmDependsFortran()
{
87
  delete this->Internal;
88 89
}

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

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

113 114 115
    // 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);
116

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

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

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

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

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

152 153 154
  // Actually write dependencies to the streams.
  typedef cmDependsFortranInternals::ObjectInfoMap ObjectInfoMap;
  ObjectInfoMap const& objInfo = this->Internal->ObjectInfo;
155 156 157 158 159
  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)) {
160 161
      return false;
    }
162
  }
163 164 165 166 167 168 169

  // 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";
170
  std::set<std::string> const& provides = this->Internal->TargetProvides;
171 172
  for (std::set<std::string>::const_iterator i = provides.begin();
       i != provides.end(); ++i) {
173
    fiStream << " " << *i << "\n";
174
  }
175 176

  // Create a script to clean the modules.
177
  if (!provides.empty()) {
178 179 180 181
    std::string fcName = this->TargetDirectory;
    fcName += "/cmake_clean_Fortran.cmake";
    cmGeneratedFileStream fcStream(fcName.c_str());
    fcStream << "# Remove fortran modules provided by this target.\n";
182
    fcStream << "FILE(REMOVE";
183 184
    std::string currentBinDir =
      this->LocalGenerator->GetCurrentBinaryDirectory();
185 186
    for (std::set<std::string>::const_iterator i = provides.begin();
         i != provides.end(); ++i) {
187 188 189 190 191 192 193 194 195 196 197 198 199
      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";
200
      fcStream << "  \""
201
               << this->MaybeConvertToRelativePath(currentBinDir, mod_lower)
202
               << "\"\n";
203
      fcStream << "  \""
204
               << this->MaybeConvertToRelativePath(currentBinDir, mod_upper)
205
               << "\"\n";
206
      fcStream << "  \""
207
               << this->MaybeConvertToRelativePath(currentBinDir, stamp)
208
               << "\"\n";
209
    }
210 211
    fcStream << "  )\n";
  }
212 213 214 215 216 217 218 219
  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;
220 221
  for (ObjectInfoMap::const_iterator infoI = objInfo.begin();
       infoI != objInfo.end(); ++infoI) {
222
    cmFortranSourceInfo const& info = infoI->second;
223 224 225
    // Include this module in the set provided by this target.
    this->Internal->TargetProvides.insert(info.Provides.begin(),
                                          info.Provides.end());
226

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

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

  // 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;
244 245
  if (const char* infoFilesValue =
        mf->GetDefinition("CMAKE_TARGET_LINKED_INFO_FILES")) {
246
    cmSystemTools::ExpandListArgument(infoFilesValue, infoFiles);
247 248 249
  }
  for (std::vector<std::string>::const_iterator i = infoFiles.begin();
       i != infoFiles.end(); ++i) {
250 251
    std::string targetDir = cmSystemTools::GetFilenamePath(*i);
    std::string fname = targetDir + "/fortran.internal";
252
    cmsys::ifstream fin(fname.c_str());
253
    if (fin) {
254
      this->MatchRemoteModules(fin, targetDir.c_str());
255
    }
256
  }
257 258 259 260
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

450 451 452
  return true;
}

453
bool cmDependsFortran::FindModule(std::string const& name, std::string& module)
454 455 456 457 458 459 460 461 462
{
  // 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;
463 464
  for (std::vector<std::string>::const_iterator i = this->IncludePath.begin();
       i != this->IncludePath.end(); ++i) {
465 466 467 468
    // Try the lower-case name.
    fullName = *i;
    fullName += "/";
    fullName += mod_lower;
469
    if (cmSystemTools::FileExists(fullName.c_str(), true)) {
470 471
      module = fullName;
      return true;
472
    }
473 474 475 476 477

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

486 487 488 489 490
bool cmDependsFortran::CopyModule(const std::vector<std::string>& args)
{
  // Implements
  //
  //   $(CMAKE_COMMAND) -E cmake_copy_f90_mod input.mod output.mod.stamp
491
  //                                          [compiler-id]
492 493 494 495 496 497 498 499
  //
  // 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];
500
  std::string compilerId;
501
  if (args.size() >= 5) {
502
    compilerId = args[4];
503
  }
504
  std::string mod_dir = cmSystemTools::GetFilenamePath(mod);
505 506 507
  if (!mod_dir.empty()) {
    mod_dir += "/";
  }
508 509 510 511
  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));
512 513 514
  mod += ".mod";
  mod_upper += ".mod";
  mod_lower += ".mod";
515 516 517 518 519 520
  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";
521
        return false;
522 523
      }
    }
524
    return true;
525 526
  }
  if (cmSystemTools::FileExists(mod_lower.c_str(), true)) {
527 528 529 530 531
    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";
532
        return false;
533 534
      }
    }
535 536
    return true;
  }
537

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

543 544 545
// 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.
546 547
static bool cmFortranStreamContainsSequence(std::istream& ifs, const char* seq,
                                            int len)
548 549 550 551
{
  assert(len > 0);

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

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

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

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

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

  return true;
}

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

  gnu < 4.9:
605 606 607 608 609 610 611 612 613 614 615
    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
616 617 618
    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.
619 620

  sun:
621
    A mod file is a binary file.  Compiling twice produces identical modules.
622 623

  others:
624
    TODO ...
625
  */
626 627 628 629 630

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

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

647 648 649 650 651
  /* Compilers which _do_ produce different mod content when the same
   * source is compiled twice
   *   -GNU
   *   -Intel
   *
652 653
   * Eat the stream content until all recompile only related changes
   * are left behind.
654
   */
655
  if (strcmp(compilerId, "GNU") == 0) {
656 657 658 659
    // 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];
660
    bool okay = !finModFile.read(reinterpret_cast<char*>(hdr), 2).fail();
661
    finModFile.seekg(0);
662
    if (!okay || hdr[0] != 0x1f || hdr[1] != 0x8b) {
663
      const char seq[1] = { '\n' };
664
      const int seqlen = 1;
665

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

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

682 683 684 685 686 687
    // 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();

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

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

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

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