cmMakefile.cxx 166 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
#include "cmMakefile.h"
13
#include "cmVersion.h"
14
#include "cmCommand.h"
15
#include "cmSourceFile.h"
16
#include "cmSourceFileLocation.h"
17
#include "cmSystemTools.h"
Ken Martin's avatar
Ken Martin committed
18
19
#include "cmGlobalGenerator.h"
#include "cmLocalGenerator.h"
20
#include "cmCommands.h"
Stephen Kelly's avatar
Stephen Kelly committed
21
#include "cmState.h"
22
#include "cmFunctionBlocker.h"
23
#include "cmListFileCache.h"
24
#include "cmCommandArgumentParserHelper.h"
25
#include "cmGeneratorExpression.h"
26
#include "cmTest.h"
27
28
29
#ifdef CMAKE_BUILD_WITH_CMAKE
#  include "cmVariableWatch.h"
#endif
30
#include "cmInstallGenerator.h"
31
#include "cmTestGenerator.h"
32
#include "cmDefinitions.h"
33
#include "cmAlgorithms.h"
34
#include "cmake.h"
35
#include <stdlib.h> // required for atoi
36
37

#include <cmsys/RegularExpression.hxx>
38
#include <cmsys/FStream.hxx>
39
40
#include <cmsys/auto_ptr.hxx>

41
#include <list>
42
#include <ctype.h> // for isspace
43
#include <assert.h>
44

45
46
47
class cmMakefile::Internals
{
public:
48
  std::list<cmDefinitions> VarStack;
49
  bool IsSourceFileTryCompile;
50
51
52

  void PushDefinitions()
  {
53
    this->VarStack.push_back(cmDefinitions());
54
55
56
57
  }

  void InitializeDefinitions(cmMakefile* parent)
  {
58
59
60
    this->VarStack.back() =
        cmDefinitions::MakeClosure(parent->Internal->VarStack.rbegin(),
                                   parent->Internal->VarStack.rend());
61
62
63
64
  }

  const char* GetDefinition(std::string const& name)
  {
65
66
    return cmDefinitions::Get(name, this->VarStack.rbegin(),
                                    this->VarStack.rend());
67
68
  }

69
70
71
72
73
74
  bool IsInitialized(std::string const& name)
  {
    return cmDefinitions::HasKey(name, this->VarStack.rbegin(),
                                 this->VarStack.rend());
  }

75
76
  void SetDefinition(std::string const& name, std::string const& value)
  {
77
    this->VarStack.back().Set(name, value.c_str());
78
79
80
81
  }

  void RemoveDefinition(std::string const& name)
  {
82
    this->VarStack.back().Set(name, 0);
83
84
  }

85
  std::vector<std::string> UnusedKeys() const
86
  {
87
    return this->VarStack.back().UnusedKeys();
88
89
  }

90
  std::vector<std::string> ClosureKeys() const
91
  {
92
93
    return cmDefinitions::ClosureKeys(this->VarStack.rbegin(),
                                      this->VarStack.rend());
94
95
96
97
  }

  void PopDefinitions()
  {
98
    this->VarStack.pop_back();
99
100
101
102
  }

  bool RaiseScope(std::string const& var, const char* varDef, cmMakefile* mf)
  {
103
    std::list<cmDefinitions>::reverse_iterator it = this->VarStack.rbegin();
104
    assert(it != this->VarStack.rend());
105
106
    ++it;
    if(it == this->VarStack.rend())
107
      {
108
109
      cmLocalGenerator* plg = mf->GetLocalGenerator()->GetParent();
      if(!plg)
110
        {
111
        return false;
112
        }
113
114
115
116
117
118
119
120
121
122
123
124
125
      // Update the definition in the parent directory top scope.  This
      // directory's scope was initialized by the closure of the parent
      // scope, so we do not need to localize the definition first.
      cmMakefile* parent = plg->GetMakefile();
      if (varDef)
        {
        parent->AddDefinition(var, varDef);
        }
      else
        {
        parent->RemoveDefinition(var);
        }
      return true;
126
      }
127
    // First localize the definition in the current scope.
128
    cmDefinitions::Raise(var, this->VarStack.rbegin(), this->VarStack.rend());
129
130
131

    // Now update the definition in the parent scope.
    it->Set(var, varDef);
132
133
    return true;
  }
134
135
};

136
// default is not to be building executables
137
cmMakefile::cmMakefile(cmLocalGenerator* localGenerator)
Stephen Kelly's avatar
Stephen Kelly committed
138
139
  : Internal(new Internals),
    LocalGenerator(localGenerator),
140
    StateSnapshot(localGenerator->GetStateSnapshot())
141
{
142
  this->Internal->PushDefinitions();
143
  this->Internal->IsSourceFileTryCompile = false;
144

145
  // Initialize these first since AddDefaultDefinitions calls AddDefinition
146
147
  this->WarnUnused = this->GetCMakeInstance()->GetWarnUnused();
  this->CheckSystemVars = this->GetCMakeInstance()->GetCheckSystemVars();
148

149
  this->Configured = false;
150
151
  this->SuppressWatches = false;

152
  // Setup the default include file regular expression (match everything).
Ken Martin's avatar
Ken Martin committed
153
  this->IncludeFileRegularExpression = "^.*$";
154
  // Setup the default include complaint regular expression (match nothing).
Ken Martin's avatar
Ken Martin committed
155
  this->ComplainFileRegularExpression = "^$";
156
  // Source and header file extensions that we can handle
157

158
  // Set up a list of source and header extensions
Alexander Neundorf's avatar
   
Alexander Neundorf committed
159
  // these are used to find files when the extension
160
  // is not given
161
  // The "c" extension MUST precede the "C" extension.
Ken Martin's avatar
Ken Martin committed
162
163
  this->SourceFileExtensions.push_back( "c" );
  this->SourceFileExtensions.push_back( "C" );
Alexander Neundorf's avatar
   
Alexander Neundorf committed
164

Ken Martin's avatar
Ken Martin committed
165
166
167
168
169
  this->SourceFileExtensions.push_back( "c++" );
  this->SourceFileExtensions.push_back( "cc" );
  this->SourceFileExtensions.push_back( "cpp" );
  this->SourceFileExtensions.push_back( "cxx" );
  this->SourceFileExtensions.push_back( "m" );
Alexander Neundorf's avatar
   
Alexander Neundorf committed
170
  this->SourceFileExtensions.push_back( "M" );
Ken Martin's avatar
Ken Martin committed
171
172
173
  this->SourceFileExtensions.push_back( "mm" );

  this->HeaderFileExtensions.push_back( "h" );
174
  this->HeaderFileExtensions.push_back( "hh" );
Ken Martin's avatar
Ken Martin committed
175
176
177
178
179
180
  this->HeaderFileExtensions.push_back( "h++" );
  this->HeaderFileExtensions.push_back( "hm" );
  this->HeaderFileExtensions.push_back( "hpp" );
  this->HeaderFileExtensions.push_back( "hxx" );
  this->HeaderFileExtensions.push_back( "in" );
  this->HeaderFileExtensions.push_back( "txx" );
Alexander Neundorf's avatar
   
Alexander Neundorf committed
181

Ken Martin's avatar
Ken Martin committed
182
  this->DefineFlags = " ";
183

184
  this->AddDefaultDefinitions();
185

186
187
188
  this->cmDefineRegex.compile("#cmakedefine[ \t]+([A-Za-z_0-9]*)");
  this->cmDefine01Regex.compile("#cmakedefine01[ \t]+([A-Za-z_0-9]*)");
  this->cmAtVarRegex.compile("(@[A-Za-z_0-9/.+-]+@)");
189
  this->cmNamedCurly.compile("^[A-Za-z0-9/_.+-]+{");
190
191
192

  // Enter a policy level for this directory.
  this->PushPolicy();
193

Brad King's avatar
Brad King committed
194
195
196
  // Protect the directory-level policies.
  this->PushPolicyBarrier();

197
198
199
  // push empty loop block
  this->PushLoopBlockBarrier();

200
201
202
  // By default the check is not done.  It is enabled by
  // cmListFileCache in the top level if necessary.
  this->CheckCMP0000 = false;
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

#if defined(CMAKE_BUILD_WITH_CMAKE)
  this->AddSourceGroup("", "^.*$");
  this->AddSourceGroup
    ("Source Files",
     "\\.(C|M|c|c\\+\\+|cc|cpp|cxx|f|f90|for|fpp"
     "|ftn|m|mm|rc|def|r|odl|idl|hpj|bat)$");
  this->AddSourceGroup("Header Files", CM_HEADER_REGEX);
  this->AddSourceGroup("CMake Rules", "\\.rule$");
  this->AddSourceGroup("Resources", "\\.plist$");
  this->AddSourceGroup("Object Files", "\\.(lo|o|obj)$");
#endif

  {
  const char* dir = this->GetCMakeInstance()->GetHomeDirectory();
  this->AddDefinition("CMAKE_SOURCE_DIR", dir);
219
  this->AddDefinition("CMAKE_CURRENT_SOURCE_DIR", dir);
220
221
222
223
  }
  {
  const char* dir = this->GetCMakeInstance()->GetHomeOutputDirectory();
  this->AddDefinition("CMAKE_BINARY_DIR", dir);
224
  this->AddDefinition("CMAKE_CURRENT_BINARY_DIR", dir);
225
  }
226
}
227

228
229
cmMakefile::~cmMakefile()
{
230
231
232
233
234
235
236
  cmDeleteAll(this->InstallGenerators);
  cmDeleteAll(this->TestGenerators);
  cmDeleteAll(this->SourceFiles);
  cmDeleteAll(this->Tests);
  cmDeleteAll(this->ImportedTargetsOwned);
  cmDeleteAll(this->FinalPassCommands);
  cmDeleteAll(this->FunctionBlockers);
Ken Martin's avatar
Ken Martin committed
237
  this->FunctionBlockers.clear();
238
239
240
241
242
  if (this->PolicyStack.size() != 1)
  {
    cmSystemTools::Error("Internal CMake Error, Policy Stack has not been"
      " popped properly");
  }
243
244
}

245
//----------------------------------------------------------------------------
Bill Hoffman's avatar
Bill Hoffman committed
246
247
void cmMakefile::IssueMessage(cmake::MessageType t,
                              std::string const& text) const
248
{
249
250
  // Collect context information.
  if(!this->CallStack.empty())
251
    {
252
    if((t == cmake::FATAL_ERROR) || (t == cmake::INTERNAL_ERROR))
253
      {
254
      this->CallStack.back().Status->SetNestedError(true);
255
      }
256
    this->GetCMakeInstance()->IssueMessage(t, text, this->GetBacktrace());
257
    }
258
  else
259
    {
260
    cmListFileContext lfc;
261
262
263
264
    // We are not currently executing a command.  Add whatever context
    // information we have.
    lfc.FilePath = this->ListFileStack.back();

265
    if(!this->GetCMakeInstance()->GetIsInTryCompile())
266
267
268
269
      {
      lfc.FilePath = this->LocalGenerator->Convert(lfc.FilePath,
                                                   cmLocalGenerator::HOME);
      }
270
    lfc.Line = 0;
271
    this->GetCMakeInstance()->IssueMessage(t, text, lfc);
272
    }
273
}
274

275
//----------------------------------------------------------------------------
Ben Boeckel's avatar
Ben Boeckel committed
276
cmListFileBacktrace cmMakefile::GetBacktrace() const
277
{
278
  cmListFileBacktrace backtrace(this->StateSnapshot);
279
280
  for(CallStackType::const_reverse_iterator i = this->CallStack.rbegin();
      i != this->CallStack.rend(); ++i)
281
    {
282
    backtrace.Append(*i->Context);
283
    }
Ben Boeckel's avatar
Ben Boeckel committed
284
  return backtrace;
285
286
}

287
288
289
290
//----------------------------------------------------------------------------
cmListFileBacktrace
cmMakefile::GetBacktrace(cmListFileContext const& lfc) const
{
291
  cmListFileBacktrace backtrace(this->StateSnapshot);
292
293
294
295
296
297
298
  backtrace.Append(lfc);
  for(CallStackType::const_reverse_iterator i = this->CallStack.rbegin();
      i != this->CallStack.rend(); ++i)
    {
    backtrace.Append(*i->Context);
    }
  return backtrace;
299
300
}

301
302
303
304
305
306
//----------------------------------------------------------------------------
cmListFileContext cmMakefile::GetExecutionContext() const
{
  return *this->CallStack.back().Context;
}

307
//----------------------------------------------------------------------------
308
void cmMakefile::PrintCommandTrace(const cmListFileFunction& lff) const
309
{
310
  std::ostringstream msg;
311
312
313
314
315
316
317
318
319
320
321
322
  msg << lff.FilePath << "(" << lff.Line << "):  ";
  msg << lff.Name << "(";
  for(std::vector<cmListFileArgument>::const_iterator i =
        lff.Arguments.begin(); i != lff.Arguments.end(); ++i)
    {
    msg << i->Value;
    msg << " ";
    }
  msg << ")";
  cmSystemTools::Message(msg.str().c_str());
}

323
//----------------------------------------------------------------------------
324
325
bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
                                cmExecutionStatus &status)
Ken Martin's avatar
Ken Martin committed
326
{
327
  bool result = true;
328

329
  // quick return if blocked
330
  if(this->IsFunctionBlocked(lff,status))
331
    {
332
333
    // No error.
    return result;
334
    }
335

Ken Martin's avatar
Ken Martin committed
336
  std::string name = lff.Name;
337

338
339
340
341
342
  // Place this call on the call stack.
  cmMakefileCall stack_manager(this, lff, status);
  static_cast<void>(stack_manager);

  // Lookup the command prototype.
343
  if(cmCommand* proto = this->GetState()->GetCommand(name))
344
345
346
347
348
349
350
    {
    // Clone the prototype.
    cmsys::auto_ptr<cmCommand> pcmd(proto->Clone());
    pcmd->SetMakefile(this);

    // Decide whether to invoke the command.
    if(pcmd->GetEnabled() && !cmSystemTools::GetFatalErrorOccured()  &&
351
352
       (this->GetCMakeInstance()->GetWorkingMode() != cmake::SCRIPT_MODE
       || pcmd->IsScriptable()))
353

354
      {
355
      // if trace is enabled, print out invoke information
Bill Hoffman's avatar
Bill Hoffman committed
356
357
      if(this->GetCMakeInstance()->GetTrace())
        {
358
        this->PrintCommandTrace(lff);
Bill Hoffman's avatar
Bill Hoffman committed
359
        }
360
361
362
      // Try invoking the command.
      if(!pcmd->InvokeInitialPass(lff.Arguments,status) ||
         status.GetNestedError())
Ken Martin's avatar
Ken Martin committed
363
        {
364
365
366
        if(!status.GetNestedError())
          {
          // The command invocation requested that we report an error.
Bill Hoffman's avatar
Bill Hoffman committed
367
          this->IssueMessage(cmake::FATAL_ERROR, pcmd->GetError());
368
          }
369
        result = false;
370
        if ( this->GetCMakeInstance()->GetWorkingMode() != cmake::NORMAL_MODE)
Ken Martin's avatar
Ken Martin committed
371
          {
372
          cmSystemTools::SetFatalErrorOccured();
Ken Martin's avatar
Ken Martin committed
373
374
          }
        }
375
      else if(pcmd->HasFinalPass())
376
377
        {
        // use the command
378
        this->FinalPassCommands.push_back(pcmd.release());
379
        }
Ken Martin's avatar
Ken Martin committed
380
      }
381
    else if ( this->GetCMakeInstance()->GetWorkingMode() == cmake::SCRIPT_MODE
382
              && !pcmd->IsScriptable() )
383
      {
384
385
386
      std::string error = "Command ";
      error += pcmd->GetName();
      error += "() is not scriptable";
Bill Hoffman's avatar
Bill Hoffman committed
387
      this->IssueMessage(cmake::FATAL_ERROR, error);
388
389
390
      result = false;
      cmSystemTools::SetFatalErrorOccured();
      }
Ken Martin's avatar
Ken Martin committed
391
392
393
    }
  else
    {
394
395
    if(!cmSystemTools::GetFatalErrorOccured())
      {
396
397
398
      std::string error = "Unknown CMake command \"";
      error += lff.Name;
      error += "\".";
Bill Hoffman's avatar
Bill Hoffman committed
399
      this->IssueMessage(cmake::FATAL_ERROR, error);
400
      result = false;
401
      cmSystemTools::SetFatalErrorOccured();
402
      }
Ken Martin's avatar
Ken Martin committed
403
    }
Alexander Neundorf's avatar
   
Alexander Neundorf committed
404

405
  return result;
Ken Martin's avatar
Ken Martin committed
406
407
}

Brad King's avatar
Brad King committed
408
409
410
411
//----------------------------------------------------------------------------
class cmMakefile::IncludeScope
{
public:
412
  IncludeScope(cmMakefile* mf, const char* fname, bool noPolicyScope);
Brad King's avatar
Brad King committed
413
414
415
416
  ~IncludeScope();
  void Quiet() { this->ReportError = false; }
private:
  cmMakefile* Makefile;
417
418
419
  const char* File;
  bool NoPolicyScope;
  bool CheckCMP0011;
Brad King's avatar
Brad King committed
420
  bool ReportError;
421
  void EnforceCMP0011();
Brad King's avatar
Brad King committed
422
423
424
};

//----------------------------------------------------------------------------
425
426
427
428
cmMakefile::IncludeScope::IncludeScope(cmMakefile* mf, const char* fname,
                                       bool noPolicyScope):
  Makefile(mf), File(fname), NoPolicyScope(noPolicyScope),
  CheckCMP0011(false), ReportError(true)
Brad King's avatar
Brad King committed
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
  if(!this->NoPolicyScope)
    {
    // Check CMP0011 to determine the policy scope type.
    switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011))
      {
      case cmPolicies::WARN:
        // We need to push a scope to detect whether the script sets
        // any policies that would affect the includer and therefore
        // requires a warning.  We use a weak scope to simulate OLD
        // behavior by allowing policy changes to affect the includer.
        this->Makefile->PushPolicy(true);
        this->CheckCMP0011 = true;
        break;
      case cmPolicies::OLD:
        // OLD behavior is to not push a scope at all.
        this->NoPolicyScope = true;
        break;
      case cmPolicies::REQUIRED_IF_USED:
      case cmPolicies::REQUIRED_ALWAYS:
        // We should never make this policy required, but we handle it
        // here just in case.
        this->CheckCMP0011 = true;
      case cmPolicies::NEW:
        // NEW behavior is to push a (strong) scope.
        this->Makefile->PushPolicy();
        break;
      }
    }

Brad King's avatar
Brad King committed
459
460
461
462
463
464
465
466
467
  // The included file cannot pop our policy scope.
  this->Makefile->PushPolicyBarrier();
}

//----------------------------------------------------------------------------
cmMakefile::IncludeScope::~IncludeScope()
{
  // Enforce matching policy scopes inside the included file.
  this->Makefile->PopPolicyBarrier(this->ReportError);
468
469
470
471
472
473
474

  if(!this->NoPolicyScope)
    {
    // If we need to enforce policy CMP0011 then the top entry is the
    // one we pushed above.  If the entry is empty, then the included
    // script did not set any policies that might affect the includer so
    // we do not need to enforce the policy.
475
    if(this->CheckCMP0011 && this->Makefile->PolicyStack.back().IsEmpty())
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
      {
      this->CheckCMP0011 = false;
      }

    // Pop the scope we pushed for the script.
    this->Makefile->PopPolicy();

    // We enforce the policy after the script's policy stack entry has
    // been removed.
    if(this->CheckCMP0011)
      {
      this->EnforceCMP0011();
      }
    }
}

//----------------------------------------------------------------------------
void cmMakefile::IncludeScope::EnforceCMP0011()
{
  // We check the setting of this policy again because the included
  // script might actually set this policy for its includer.
  switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011))
    {
    case cmPolicies::WARN:
      // Warn because the user did not set this policy.
      {
502
      std::ostringstream w;
Stephen Kelly's avatar
Stephen Kelly committed
503
      w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0011) << "\n"
504
505
506
507
508
509
510
511
512
513
        << "The included script\n  " << this->File << "\n"
        << "affects policy settings.  "
        << "CMake is implying the NO_POLICY_SCOPE option for compatibility, "
        << "so the effects are applied to the including context.";
      this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
      }
      break;
    case cmPolicies::REQUIRED_IF_USED:
    case cmPolicies::REQUIRED_ALWAYS:
      {
514
      std::ostringstream e;
Stephen Kelly's avatar
Stephen Kelly committed
515
      e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0011) << "\n"
516
517
518
519
520
521
522
523
524
525
526
527
        << "The included script\n  " << this->File << "\n"
        << "affects policy settings, so it requires this policy to be set.";
      this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
      }
      break;
    case cmPolicies::OLD:
    case cmPolicies::NEW:
      // The script set this policy.  We assume the purpose of the
      // script is to initialize policies for its includer, and since
      // the policy is now set for later scripts, we do not warn.
      break;
    }
Brad King's avatar
Brad King committed
528
529
}

530
531
bool cmMakefile::ProcessBuildsystemFile(const char* listfile)
{
532
  this->AddDefinition("CMAKE_PARENT_LIST_FILE", listfile);
533
  std::string curSrc = this->GetCurrentSourceDirectory();
534
535
536
537
  bool result = this->ReadListFile(listfile, true,
                                   curSrc == this->GetHomeDirectory());
  this->EnforceDirectoryLevelRules();
  return result;
538
539
}

540
541
bool cmMakefile::ReadDependentFile(const char* listfile, bool noPolicyScope)
{
542
543
  this->AddDefinition("CMAKE_PARENT_LIST_FILE",
                      this->GetDefinition("CMAKE_CURRENT_LIST_FILE"));
544
545
546
  bool result = this->ReadListFile(listfile, noPolicyScope, false);
  this->ListFileStack.pop_back();
  return result;
547
548
549
550
}

bool cmMakefile::ReadListFile(const char* listfile)
{
551
552
553
  bool result = this->ReadListFile(listfile, true, false);
  this->ListFileStack.pop_back();
  return result;
554
555
}

556
bool cmMakefile::ReadListFile(const char* listfile,
557
558
                              bool noPolicyScope,
                              bool requireProjectCommand)
559
{
560
561
  std::string filenametoread =
    cmSystemTools::CollapseFullPath(listfile,
562
                                    this->GetCurrentSourceDirectory());
563

564
565
566
  this->ListFileStack.push_back(filenametoread);

  cmListFile listFile;
567
568
  if (!listFile.ParseFile(filenametoread.c_str(),
                          requireProjectCommand, this))
569
    {
570
    return false;
571
572
    }

573
574
575
  // add this list file to the list of dependencies
  this->ListFiles.push_back(filenametoread);

576
577
578
579
580
  std::string currentParentFile
      = this->GetSafeDefinition("CMAKE_PARENT_LIST_FILE");
  std::string currentFile
    = this->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE");

581
582
583
584
  this->AddDefinition("CMAKE_CURRENT_LIST_FILE", filenametoread.c_str());
  this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
                       cmSystemTools::GetFilenamePath(filenametoread).c_str());

585
  this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
586
587
588
  this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");

589
590
  this->ReadListFileInternal(listFile, filenametoread.c_str(), noPolicyScope);
  this->CheckForUnusedVariables();
591
592
593
594
595
596
597
598
599

  this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentParentFile.c_str());
  this->AddDefinition("CMAKE_CURRENT_LIST_FILE", currentFile.c_str());
  this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
                      cmSystemTools::GetFilenamePath(currentFile).c_str());
  this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");

600
  return true;
601
602
}

Stephen Kelly's avatar
Stephen Kelly committed
603
void cmMakefile::ReadListFileInternal(cmListFile const& listFile,
604
605
                                      const char* filenametoread,
                                      bool noPolicyScope)
606
{
607
  // Enforce balanced blocks (if/endif, function/endfunction, etc.).
608
  IncludeScope incScope(this, filenametoread, noPolicyScope);
609
  LexicalPushPop lexScope(this);
610
611

  // Run the parsed commands.
Stephen Kelly's avatar
Stephen Kelly committed
612
  const size_t numberFunctions = listFile.Functions.size();
613
  for(size_t i =0; i < numberFunctions; ++i)
614
    {
615
    cmExecutionStatus status;
Stephen Kelly's avatar
Stephen Kelly committed
616
    this->ExecuteCommand(listFile.Functions[i],status);
617
    if(cmSystemTools::GetFatalErrorOccured())
618
      {
619
620
      // Exit early due to error.
      lexScope.Quiet();
Brad King's avatar
Brad King committed
621
      incScope.Quiet();
622
623
624
625
626
      break;
      }
    if(status.GetReturnInvoked())
      {
      // Exit early due to return command.
627
      break;
628
      }
629
630
    }
}
631

632
//----------------------------------------------------------------------------
633
void cmMakefile::EnforceDirectoryLevelRules() const
634
635
636
637
{
  // Diagnose a violation of CMP0000 if necessary.
  if(this->CheckCMP0000)
    {
638
    std::ostringstream msg;
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    msg << "No cmake_minimum_required command is present.  "
        << "A line of code such as\n"
        << "  cmake_minimum_required(VERSION "
        << cmVersion::GetMajorVersion() << "."
        << cmVersion::GetMinorVersion()
        << ")\n"
        << "should be added at the top of the file.  "
        << "The version specified may be lower if you wish to "
        << "support older CMake versions for this project.  "
        << "For more information run "
        << "\"cmake --help-policy CMP0000\".";
    switch (this->GetPolicyStatus(cmPolicies::CMP0000))
      {
      case cmPolicies::WARN:
        // Warn because the user did not provide a mimimum required
        // version.
Stephen Kelly's avatar
Stephen Kelly committed
655
        this->IssueMessage(cmake::AUTHOR_WARNING, msg.str());
656
657
658
659
660
661
662
663
      case cmPolicies::OLD:
        // OLD behavior is to use policy version 2.4 set in
        // cmListFileCache.
        break;
      case cmPolicies::REQUIRED_IF_USED:
      case cmPolicies::REQUIRED_ALWAYS:
      case cmPolicies::NEW:
        // NEW behavior is to issue an error.
Stephen Kelly's avatar
Stephen Kelly committed
664
        this->IssueMessage(cmake::FATAL_ERROR, msg.str());
665
666
667
668
669
        cmSystemTools::SetFatalErrorOccured();
        return;
      }
    }
}
670

671
672
namespace
{
673
  struct file_not_persistent
674
675
  {
    bool operator()(const std::string& path) const
676
677
678
679
      {
      return !(path.find("CMakeTmp") == path.npos &&
               cmSystemTools::FileExists(path.c_str()));
      }
680
681
682
  };
}

683
void cmMakefile::FinalPass()
684
685
{
  // do all the variable expansions here
686
  this->ExpandVariablesCMP0019();
687

688
  // give all the commands a chance to do something
689
  // after the file has been parsed before generation
690
691
  for(std::vector<cmCommand*>::iterator i = this->FinalPassCommands.begin();
      i != this->FinalPassCommands.end(); ++i)
692
693
    {
    (*i)->FinalPass();
694
    }
695

696
697
698
699
700
701
702
  //go through all configured files and see which ones still exist.
  //we don't want cmake to re-run if a configured file is created and deleted
  //during processing as that would make it a transient file that can't
  //influence the build process

  //remove_if will move all items that don't have a valid file name to the
  //back of the vector
703
704
705
706
  std::vector<std::string>::iterator new_output_files_end = std::remove_if(
                                                     this->OutputFiles.begin(),
                                                     this->OutputFiles.end(),
                                                     file_not_persistent() );
707
  //we just have to erase all items at the back
708
709
710
711
712
713
714
715
716
  this->OutputFiles.erase(new_output_files_end, this->OutputFiles.end() );

  //if a configured file is used as input for another configured file,
  //and then deleted it will show up in the input list files so we
  //need to scan those too
  std::vector<std::string>::iterator new_list_files_end = std::remove_if(
                                                   this->ListFiles.begin(),
                                                   this->ListFiles.end(),
                                                   file_not_persistent() );
717

718
  this->ListFiles.erase(new_list_files_end, this->ListFiles.end() );
719
720
}

Bill Hoffman's avatar
Bill Hoffman committed
721
// Generate the output file
722
void cmMakefile::ConfigureFinalPass()
723
724
{
  this->FinalPass();
725
726
  const char* oldValue
    = this->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
727
728
  if (oldValue && cmSystemTools::VersionCompare(
        cmSystemTools::OP_LESS, oldValue, "2.4"))
729
    {
730
731
732
733
734
735
    this->IssueMessage(
      cmake::FATAL_ERROR,
      "You have set CMAKE_BACKWARDS_COMPATIBILITY to a CMake version less "
      "than 2.4. This version of CMake only supports backwards compatibility "
      "with CMake 2.4 or later. For compatibility with older versions please "
      "use any CMake 2.8.x release or lower.");
736
    }
Ken Martin's avatar
Ken Martin committed
737
738
  for (cmTargets::iterator l = this->Targets.begin();
       l != this->Targets.end(); l++)
739
    {
740
741
742
743
    if (l->second.GetType() == cmTarget::INTERFACE_LIBRARY)
      {
      continue;
      }
744
    l->second.FinishConfigure();
745
    }
746
747
}

748
749
//----------------------------------------------------------------------------
void
750
cmMakefile::AddCustomCommandToTarget(const std::string& target,
751
                                   const std::vector<std::string>& byproducts,
752
753
754
                                     const std::vector<std::string>& depends,
                                     const cmCustomCommandLines& commandLines,
                                     cmTarget::CustomCommandType type,
755
                                     const char* comment,
756
                                     const char* workingDir,
757
                                     bool escapeOldStyle,
758
                                     bool uses_terminal)
759
{
760
  // Find the target to which to add the custom command.
Ken Martin's avatar
Ken Martin committed
761
  cmTargets::iterator ti = this->Targets.find(target);
762
763

  if(ti == this->Targets.end())
764
    {
765
766
    cmake::MessageType messageType = cmake::AUTHOR_WARNING;
    bool issueMessage = false;
767
    std::ostringstream e;
768
    switch(this->GetPolicyStatus(cmPolicies::CMP0040))
Brad King's avatar
Brad King committed
769
      {
770
      case cmPolicies::WARN:
Stephen Kelly's avatar
Stephen Kelly committed
771
        e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0040) << "\n";
772
773
774
775
776
777
778
779
        issueMessage = true;
      case cmPolicies::OLD:
        break;
      case cmPolicies::NEW:
      case cmPolicies::REQUIRED_IF_USED:
      case cmPolicies::REQUIRED_ALWAYS:
        issueMessage = true;
        messageType = cmake::FATAL_ERROR;
Brad King's avatar
Brad King committed
780
      }
781
782

    if(issueMessage)
783
      {
784
      e << "The target name \"" << target << "\" is unknown in this context.";
Stephen Kelly's avatar
Stephen Kelly committed
785
      IssueMessage(messageType, e.str());
786
      }
787
788
789
790
791
792

      return;
    }

  if(ti->second.GetType() == cmTarget::OBJECT_LIBRARY)
    {
793
    std::ostringstream e;
794
795
796
797
798
    e << "Target \"" << target << "\" is an OBJECT library "
      "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
    this->IssueMessage(cmake::FATAL_ERROR, e.str());
    return;
    }
799
800
  if(ti->second.GetType() == cmTarget::INTERFACE_LIBRARY)
    {
801
    std::ostringstream e;
802
803
804
805
806
    e << "Target \"" << target << "\" is an INTERFACE library "
      "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
    this->IssueMessage(cmake::FATAL_ERROR, e.str());
    return;
    }
807
808
809
810
811
812
813
814
815
816
817

  // Always create the byproduct sources and mark them generated.
  for(std::vector<std::string>::const_iterator o = byproducts.begin();
      o != byproducts.end(); ++o)
    {
    if(cmSourceFile* out = this->GetOrCreateSource(*o, true))
      {
      out->SetProperty("GENERATED", "1");
      }
    }

818
819
  // Add the command to the appropriate build step for the target.
  std::vector<std::string> no_output;
820
  cmCustomCommand cc(this, no_output, byproducts, depends,
821
822
823
                     commandLines, comment, workingDir);
  cc.SetEscapeOldStyle(escapeOldStyle);
  cc.SetEscapeAllowMakeVars(true);
824
  cc.SetUsesTerminal(uses_terminal);
825
826
827
828
829
830
831
832
833
834
835
  switch(type)
    {
    case cmTarget::PRE_BUILD:
      ti->second.AddPreBuildCommand(cc);
      break;
    case cmTarget::PRE_LINK:
      ti->second.AddPreLinkCommand(cc);
      break;
    case cmTarget::POST_BUILD:
      ti->second.AddPostBuildCommand(cc);
      break;
836
837
838
    }
}

839
//----------------------------------------------------------------------------
840
cmSourceFile*
841
cmMakefile::AddCustomCommandToOutput(const std::vector<std::string>& outputs,
842
                                  const std::vector<std::string>& byproducts,
843
                                     const std::vector<std::string>& depends,
844
                                     const std::string& main_dependency,
845
846
                                     const cmCustomCommandLines& commandLines,
                                     const char* comment,
847
                                     const char* workingDir,
848
                                     bool replace,
849
850
                                     bool escapeOldStyle,
                                     bool uses_terminal)
851
{
852
853
854
855
  // Make sure there is at least one output.
  if(outputs.empty())
    {
    cmSystemTools::Error("Attempt to add a custom rule with no output!");
856
    return 0;
857
858
    }

859
860
861
862
863
864
865
  // Validate custom commands.  TODO: More strict?
  for(cmCustomCommandLines::const_iterator i=commandLines.begin();
      i != commandLines.end(); ++i)
    {
    cmCustomCommandLine const& cl = *i;
    if(!cl.empty() && !cl[0].empty() && cl[0][0] == '"')
      {
866
      std::ostringstream e;
867
868
      e << "COMMAND may not contain literal quotes:\n  " << cl[0] << "\n";
      this->IssueMessage(cmake::FATAL_ERROR, e.str());
869
      return 0;
870
871
872
      }
    }

873
874
  // Choose a source file on which to store the custom command.
  cmSourceFile* file = 0;
875
  if(!commandLines.empty() && !main_dependency.empty())
876
877
878
879
880
    {
    // The main dependency was specified.  Use it unless a different
    // custom command already used it.
    file = this->GetSource(main_dependency);
    if(file && file->GetCustomCommand() && !replace)
881
      {
882
883
      // The main dependency already has a custom command.
      if(commandLines == file->GetCustomCommand()->GetCommandLines())
884
        {
885
886
        // The existing custom command is identical.  Silently ignore
        // the duplicate.
887
        return file;
888
889
890
        }
      else
        {
891
892
893
        // The existing custom command is different.  We need to
        // generate a rule file for this new command.
        file = 0;
894
        }
895
      }
896
    else if (!file)
897
      {
898
      file = this->CreateSource(main_dependency);
899
900
901
      }
    }

902
903
  // Generate a rule file if the main dependency is not available.
  if(!file)
904
    {
905
    cmGlobalGenerator* gg = this->GetGlobalGenerator();
906

907
    // Construct a rule file associated with the first output produced.
908
909
    std::string outName = gg->GenerateRuleFile(outputs[0]);

910
    // Check if the rule file already exists.
Stephen Kelly's avatar
Stephen Kelly committed
911
    file = this->GetSource(outName);
912
    if(file && file->GetCustomCommand() && !replace)
913
      {
914
915
      // The rule file already exists.
      if(commandLines != file->GetCustomCommand()->GetCommandLines())
916
        {
917
        cmSystemTools::Error("Attempt to add a custom rule to output \"",
918
919
                             outName.c_str(),
                             "\" which already has a custom rule.");
920
        }
921
      return file;
922
      }
923
924

    // Create a cmSourceFile for the rule file.
925
926
927
928
    if (!file)
      {
      file = this->CreateSource(outName, true);
      }
929
    file->SetProperty("__CMAKE_RULE", "1");
930
    }
931

932
933
934
  // Always create the output sources and mark them generated.
  for(std::vector<std::string>::const_iterator o = outputs.begin();
      o != outputs.end(); ++o)
935
    {
Stephen Kelly's avatar
Stephen Kelly committed
936
    if(cmSourceFile* out = this->GetOrCreateSource(*o, true))
937
938
939
      {
      out->SetProperty("GENERATED", "1");
      }