cmDependsFortran.cxx 24.4 KB
Newer Older
1
2
3
/*============================================================================
  CMake - Cross Platform Makefile Generator
  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
4

5
6
  Distributed under the OSI-approved BSD License (the "License");
  see accompanying file Copyright.txt for details.
7

8
9
10
11
  This software is distributed WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the License for more information.
============================================================================*/
12
13
#include "cmDependsFortran.h"

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

21
#include <assert.h>
22
#include <cmsys/FStream.hxx>
23
24
25
26
27
#include <iostream>
#include <map>
#include <stdlib.h>
#include <string.h>
#include <utility>
28

29
30
31
32
// 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.

33
34
35
36
class cmDependsFortranInternals
{
public:
  // The set of modules provided by this target.
37
  std::set<std::string> TargetProvides;
38
39

  // Map modules required by this target to locations.
40
  typedef std::map<std::string, std::string> TargetRequiresMap;
41
42
43
  TargetRequiresMap TargetRequires;

  // Information about each object file.
44
  typedef std::map<std::string, cmFortranSourceInfo> ObjectInfoMap;
45
46
  ObjectInfoMap ObjectInfo;

47
48
  cmFortranSourceInfo& CreateObjectInfo(const char* obj, const char* src)
  {
49
    std::map<std::string, cmFortranSourceInfo>::iterator i =
50
      this->ObjectInfo.find(obj);
51
52
53
    if (i == this->ObjectInfo.end()) {
      std::map<std::string, cmFortranSourceInfo>::value_type entry(
        obj, cmFortranSourceInfo());
54
55
56
      i = this->ObjectInfo.insert(entry).first;
      i->second.Source = src;
    }
57
58
    return i->second;
  }
59
60
};

61
cmDependsFortran::cmDependsFortran()
Daniel Pfeifer's avatar
Daniel Pfeifer committed
62
  : Internal(CM_NULLPTR)
63
64
65
{
}

66
67
68
cmDependsFortran::cmDependsFortran(cmLocalGenerator* lg)
  : cmDepends(lg)
  , Internal(new cmDependsFortranInternals)
69
{
70
71
72
  // Configure the include file search path.
  this->SetIncludePathFromLanguage("Fortran");

73
74
75
  // Get the list of definitions.
  std::vector<std::string> definitions;
  cmMakefile* mf = this->LocalGenerator->GetMakefile();
76
77
  if (const char* c_defines =
        mf->GetDefinition("CMAKE_TARGET_DEFINITIONS_Fortran")) {
78
    cmSystemTools::ExpandListArgument(c_defines, definitions);
79
  }
80

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

cmDependsFortran::~cmDependsFortran()
{
96
  delete this->Internal;
97
98
}

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

114
  bool okay = true;
115
116
  for (std::set<std::string>::const_iterator it = sources.begin();
       it != sources.end(); ++it) {
117
118
    const std::string& src = *it;
    // Get the information object for this source.
119
    cmFortranSourceInfo& info =
120
      this->Internal->CreateObjectInfo(obj.c_str(), src.c_str());
121

122
123
124
    // 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);
125

126
    // Push on the starting file.
127
    cmFortranParser_FilePush(&parser, src.c_str());
128

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

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

150
  // Get the directory in which stamp files will be stored.
151
  const char* stamp_dir = this->TargetDirectory.c_str();
152
153
154

  // Get the directory in which module files will be created.
  cmMakefile* mf = this->LocalGenerator->GetMakefile();
155
156
  std::string mod_dir =
    mf->GetSafeDefinition("CMAKE_Fortran_TARGET_MODULE_DIR");
157
158
159
  if (mod_dir.empty()) {
    mod_dir = this->LocalGenerator->GetCurrentBinaryDirectory();
  }
160

161
162
163
  // Actually write dependencies to the streams.
  typedef cmDependsFortranInternals::ObjectInfoMap ObjectInfoMap;
  ObjectInfoMap const& objInfo = this->Internal->ObjectInfo;
164
165
166
167
168
  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)) {
169
170
      return false;
    }
171
  }
172
173
174
175
176
177
178

  // 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";
179
  std::set<std::string> const& provides = this->Internal->TargetProvides;
180
181
  for (std::set<std::string>::const_iterator i = provides.begin();
       i != provides.end(); ++i) {
182
    fiStream << " " << *i << "\n";
183
  }
184
185

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

237
238
    for (std::set<std::string>::const_iterator i = info.Requires.begin();
         i != info.Requires.end(); ++i) {
239
240
      this->Internal->TargetRequires[*i] = "";
    }
241
  }
242
243

  // Short-circuit for simple targets.
244
  if (this->Internal->TargetRequires.empty()) {
245
    return;
246
  }
247
248
249
250
251
252
253

  // 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;
254
255
  if (const char* infoFilesValue =
        mf->GetDefinition("CMAKE_TARGET_LINKED_INFO_FILES")) {
256
    cmSystemTools::ExpandListArgument(infoFilesValue, infoFiles);
257
258
259
  }
  for (std::vector<std::string>::const_iterator i = infoFiles.begin();
       i != infoFiles.end(); ++i) {
260
261
    std::string targetDir = cmSystemTools::GetFilenamePath(*i);
    std::string fname = targetDir + "/fortran.internal";
262
    cmsys::ifstream fin(fname.c_str());
263
    if (fin) {
264
      this->MatchRemoteModules(fin, targetDir.c_str());
265
    }
266
  }
267
268
269
270
}

void cmDependsFortran::MatchLocalModules()
{
271
  const char* stampDir = this->TargetDirectory.c_str();
272
  std::set<std::string> const& provides = this->Internal->TargetProvides;
273
274
  for (std::set<std::string>::const_iterator i = provides.begin();
       i != provides.end(); ++i) {
275
    this->ConsiderModule(i->c_str(), stampDir);
276
  }
277
278
279
}

void cmDependsFortran::MatchRemoteModules(std::istream& fin,
280
                                          const char* stampDir)
281
282
{
  std::string line;
283
  bool doing_provides = false;
284
  while (cmSystemTools::GetLineFromStream(fin, line)) {
285
    // Ignore comments and empty lines.
286
    if (line.empty() || line[0] == '#' || line[0] == '\r') {
287
      continue;
288
    }
289

290
291
292
    if (line[0] == ' ') {
      if (doing_provides) {
        this->ConsiderModule(line.c_str() + 1, stampDir);
293
      }
294
    } else if (line == "provides") {
295
      doing_provides = true;
296
    } else {
297
298
      doing_provides = false;
    }
299
  }
300
301
}

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

319
320
321
322
323
324
bool cmDependsFortran::WriteDependenciesReal(const char* obj,
                                             cmFortranSourceInfo const& info,
                                             std::string const& mod_dir,
                                             const char* stamp_dir,
                                             std::ostream& makeDepends,
                                             std::ostream& internalDepends)
325
326
327
328
329
330
{
  typedef cmDependsFortranInternals::TargetRequiresMap TargetRequiresMap;

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

331
  // Write the include dependencies to the output stream.
332
333
  std::string obj_i = this->LocalGenerator->ConvertToRelativePath(
    obj, cmOutputConverter::HOME_OUTPUT);
334
  std::string obj_m = this->LocalGenerator->ConvertToOutputFormat(
335
    obj_i, cmOutputConverter::MAKERULE);
336
  internalDepends << obj_i << std::endl;
337
  internalDepends << " " << src << std::endl;
338
339
340
  for (std::set<std::string>::const_iterator i = info.Includes.begin();
       i != info.Includes.end(); ++i) {
    makeDepends << obj_m << ": "
341
342
343
                << this->LocalGenerator->Convert(
                     *i, cmOutputConverter::HOME_OUTPUT,
                     cmOutputConverter::MAKERULE)
344
                << std::endl;
345
    internalDepends << " " << *i << std::endl;
346
  }
347
  makeDepends << std::endl;
348

349
  // Write module requirements to the output stream.
350
351
  for (std::set<std::string>::const_iterator i = info.Requires.begin();
       i != info.Requires.end(); ++i) {
352
    // Require only modules not provided in the same source.
353
354
    if (std::set<std::string>::const_iterator(info.Provides.find(*i)) !=
        info.Provides.end()) {
355
      continue;
356
    }
357
358
359

    // If the module is provided in this target special handling is
    // needed.
360
361
    if (this->Internal->TargetProvides.find(*i) !=
        this->Internal->TargetProvides.end()) {
362
363
364
      // The module is provided by a different source in the same
      // target.  Add the proxy dependency to make sure the other
      // source builds first.
365
      std::string proxy = stamp_dir;
366
367
368
      proxy += "/";
      proxy += *i;
      proxy += ".mod.proxy";
369
      proxy = this->LocalGenerator->Convert(
370
        proxy, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::MAKERULE);
371

372
      // since we require some things add them to our list of requirements
373
      makeDepends << obj_m << ".requires: " << proxy << std::endl;
374
    }
375

376
377
378
379
    // The object file should depend on timestamped files for the
    // modules it uses.
    TargetRequiresMap::const_iterator required =
      this->Internal->TargetRequires.find(*i);
380
381
382
383
    if (required == this->Internal->TargetRequires.end()) {
      abort();
    }
    if (!required->second.empty()) {
384
      // This module is known.  Depend on its timestamp file.
385
      std::string stampFile = this->LocalGenerator->Convert(
386
387
        required->second, cmOutputConverter::HOME_OUTPUT,
        cmOutputConverter::MAKERULE);
388
      makeDepends << obj_m << ": " << stampFile << "\n";
389
    } else {
390
391
392
      // This module is not known to CMake.  Try to locate it where
      // the compiler will and depend on that.
      std::string module;
393
394
      if (this->FindModule(*i, module)) {
        module = this->LocalGenerator->Convert(
395
          module, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::MAKERULE);
396
        makeDepends << obj_m << ": " << module << "\n";
397
398
      }
    }
399
  }
400
401

  // Write provided modules to the output stream.
402
403
  for (std::set<std::string>::const_iterator i = info.Provides.begin();
       i != info.Provides.end(); ++i) {
404
    std::string proxy = stamp_dir;
405
406
407
    proxy += "/";
    proxy += *i;
    proxy += ".mod.proxy";
408
409
    proxy = this->LocalGenerator->Convert(
      proxy, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::MAKERULE);
410
    makeDepends << proxy << ": " << obj_m << ".provides" << std::endl;
411
  }
412

413
  // If any modules are provided then they must be converted to stamp files.
414
  if (!info.Provides.empty()) {
415
416
    // Create a target to copy the module after the object file
    // changes.
417
    makeDepends << obj_m << ".provides.build:\n";
418
419
    for (std::set<std::string>::const_iterator i = info.Provides.begin();
         i != info.Provides.end(); ++i) {
420
421
422
      // Include this module in the set provided by this target.
      this->Internal->TargetProvides.insert(*i);

423
424
425
      // 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.
426
      std::string m = cmSystemTools::LowerCase(*i);
427
428
429
      std::string modFile = mod_dir;
      modFile += "/";
      modFile += *i;
430
      modFile = this->LocalGenerator->Convert(
431
        modFile, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::SHELL);
432
      std::string stampFile = stamp_dir;
433
434
435
      stampFile += "/";
      stampFile += m;
      stampFile += ".mod.stamp";
436
      stampFile = this->LocalGenerator->Convert(
437
        stampFile, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::SHELL);
438
439
      makeDepends << "\t$(CMAKE_COMMAND) -E cmake_copy_f90_mod " << modFile
                  << " " << stampFile;
440
441
      cmMakefile* mf = this->LocalGenerator->GetMakefile();
      const char* cid = mf->GetDefinition("CMAKE_Fortran_COMPILER_ID");
442
      if (cid && *cid) {
443
        makeDepends << " " << cid;
444
      }
445
446
      makeDepends << "\n";
    }
447
448
    // After copying the modules update the timestamp file so that
    // copying will not be done again until the source rebuilds.
449
    makeDepends << "\t$(CMAKE_COMMAND) -E touch " << obj_m
Bill Hoffman's avatar
Bill Hoffman committed
450
                << ".provides.build\n";
451
452
453

    // Make sure the module timestamp rule is evaluated by the time
    // the target finishes building.
454
455
    std::string driver = this->TargetDirectory;
    driver += "/build";
456
    driver = this->LocalGenerator->Convert(
457
      driver, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::MAKERULE);
458
    makeDepends << driver << ": " << obj_m << ".provides.build\n";
459
  }
460

461
462
463
  return true;
}

464
bool cmDependsFortran::FindModule(std::string const& name, std::string& module)
465
466
467
468
469
470
471
472
473
{
  // 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;
474
475
  for (std::vector<std::string>::const_iterator i = this->IncludePath.begin();
       i != this->IncludePath.end(); ++i) {
476
477
478
479
    // Try the lower-case name.
    fullName = *i;
    fullName += "/";
    fullName += mod_lower;
480
    if (cmSystemTools::FileExists(fullName.c_str(), true)) {
481
482
      module = fullName;
      return true;
483
    }
484
485
486
487
488

    // Try the upper-case name.
    fullName = *i;
    fullName += "/";
    fullName += mod_upper;
489
    if (cmSystemTools::FileExists(fullName.c_str(), true)) {
490
491
492
      module = fullName;
      return true;
    }
493
  }
494
495
496
  return false;
}

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

549
550
  std::cerr << "Error copying Fortran module \"" << args[2] << "\".  Tried \""
            << mod_upper << "\" and \"" << mod_lower << "\".\n";
551
552
553
  return false;
}

554
555
556
// 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.
557
558
static bool cmFortranStreamContainsSequence(std::istream& ifs, const char* seq,
                                            int len)
559
560
561
562
{
  assert(len > 0);

  int cur = 0;
563
  while (cur < len) {
564
565
    // Get the next character.
    int token = ifs.get();
566
    if (!ifs) {
567
      return false;
568
    }
569
570

    // Check the character.
571
    if (token == static_cast<int>(seq[cur])) {
572
      ++cur;
573
    } else {
574
575
576
      // Assume the sequence has no repeating subsequence.
      cur = 0;
    }
577
  }
578
579
580
581
582
583

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

// Helper function to compare the remaining content in two streams.
584
static bool cmFortranStreamsDiffer(std::istream& ifs1, std::istream& ifs2)
585
586
{
  // Compare the remaining content.
587
  for (;;) {
588
589
    int ifs1_c = ifs1.get();
    int ifs2_c = ifs2.get();
590
    if (!ifs1 && !ifs2) {
591
592
593
      // We have reached the end of both streams simultaneously.
      // The streams are identical.
      return false;
594
    }
595

596
    if (!ifs1 || !ifs2 || ifs1_c != ifs2_c) {
597
598
599
600
      // We have reached the end of one stream before the other or
      // found differing content.  The streams are different.
      break;
    }
601
  }
602
603
604
605

  return true;
}

606
bool cmDependsFortran::ModulesDiffer(const char* modFile,
607
608
                                     const char* stampFile,
                                     const char* compilerId)
609
610
{
  /*
611
612
613
614
615
  gnu >= 4.9:
    A mod file is an ascii file compressed with gzip.
    Compiling twice produces identical modules.

  gnu < 4.9:
616
617
618
619
620
621
622
623
624
625
626
    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
627
628
629
    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.
630
631

  sun:
632
    A mod file is a binary file.  Compiling twice produces identical modules.
633
634

  others:
635
    TODO ...
636
  */
637
638
639
640
641

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

646
#if defined(_WIN32) || defined(__CYGWIN__)
647
648
  cmsys::ifstream finModFile(modFile, std::ios::in | std::ios::binary);
  cmsys::ifstream finStampFile(stampFile, std::ios::in | std::ios::binary);
649
#else
650
651
  cmsys::ifstream finModFile(modFile);
  cmsys::ifstream finStampFile(stampFile);
652
#endif
653
  if (!finModFile || !finStampFile) {
654
655
    // At least one of the files does not exist.  The modules differ.
    return true;
656
  }
657

658
659
660
661
662
  /* Compilers which _do_ produce different mod content when the same
   * source is compiled twice
   *   -GNU
   *   -Intel
   *
663
664
   * Eat the stream content until all recompile only related changes
   * are left behind.
665
   */
666
  if (strcmp(compilerId, "GNU") == 0) {
667
668
669
670
    // 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
671
    bool okay = !finModFile.read(reinterpret_cast<char*>(hdr), 2).fail();
672
    finModFile.seekg(0);
Daniel Pfeifer's avatar
Daniel Pfeifer committed
673
    if (!okay || hdr[0] != 0x1f || hdr[1] != 0x8b) {
674
      const char seq[1] = { '\n' };
675
      const int seqlen = 1;
676

677
      if (!cmFortranStreamContainsSequence(finModFile, seq, seqlen)) {
678
679
680
681
        // The module is of unexpected format.  Assume it is different.
        std::cerr << compilerId << " fortran module " << modFile
                  << " has unexpected format." << std::endl;
        return true;
682
      }
683

684
      if (!cmFortranStreamContainsSequence(finStampFile, seq, seqlen)) {
685
686
        // The stamp must differ if the sequence is not contained.
        return true;
687
      }
688
    }
689
690
  } else if (strcmp(compilerId, "Intel") == 0) {
    const char seq[2] = { '\n', '\0' };
691
    const int seqlen = 2;
692

693
694
695
696
697
698
    // 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();

699
    if (!cmFortranStreamContainsSequence(finModFile, seq, seqlen)) {
700
701
702
703
      // The module is of unexpected format.  Assume it is different.
      std::cerr << compilerId << " fortran module " << modFile
                << " has unexpected format." << std::endl;
      return true;
704
    }
705

706
    if (!cmFortranStreamContainsSequence(finStampFile, seq, seqlen)) {
707
708
      // The stamp must differ if the sequence is not contained.
      return true;
709
    }
710
  }
711

712
  // Compare the remaining content.  If no compiler id matched above,
713
714
  // including the case none was given, this will compare the whole
  // content.
715
  return cmFortranStreamsDiffer(finModFile, finStampFile);
716
}