blob: cb66a75a27dc43ebc9282bfeb996f5cbc88781b3 [file] [log] [blame]
/*============================================================================
CMake - Cross Platform Makefile Generator
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
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.
============================================================================*/
#include "cmMakefile.h"
#include "cmVersion.h"
#include "cmCommand.h"
#include "cmSourceFile.h"
#include "cmSourceFileLocation.h"
#include "cmSystemTools.h"
#include "cmGlobalGenerator.h"
#include "cmCommands.h"
#include "cmState.h"
#include "cmOutputConverter.h"
#include "cmFunctionBlocker.h"
#include "cmGeneratorExpressionEvaluationFile.h"
#include "cmListFileCache.h"
#include "cmCommandArgumentParserHelper.h"
#include "cmGeneratorExpression.h"
#include "cmTest.h"
#ifdef CMAKE_BUILD_WITH_CMAKE
# include "cmVariableWatch.h"
#endif
#include "cmInstallGenerator.h"
#include "cmTestGenerator.h"
#include "cmAlgorithms.h"
#include "cmake.h"
#include <stdlib.h> // required for atoi
#include <cmsys/RegularExpression.hxx>
#include <cmsys/FStream.hxx>
#include <cmsys/auto_ptr.hxx>
#include <list>
#include <ctype.h> // for isspace
#include <assert.h>
// default is not to be building executables
cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
cmState::Snapshot const& snapshot)
: GlobalGenerator(globalGenerator),
StateSnapshot(snapshot)
{
this->IsSourceFileTryCompile = false;
// Initialize these first since AddDefaultDefinitions calls AddDefinition
this->WarnUnused = this->GetCMakeInstance()->GetWarnUnused();
this->CheckSystemVars = this->GetCMakeInstance()->GetCheckSystemVars();
this->SuppressWatches = false;
// Setup the default include file regular expression (match everything).
this->SetProperty("INCLUDE_REGULAR_EXPRESSION", "^.*$");
// Setup the default include complaint regular expression (match nothing).
this->ComplainFileRegularExpression = "^$";
// Source and header file extensions that we can handle
// Set up a list of source and header extensions
// these are used to find files when the extension
// is not given
// The "c" extension MUST precede the "C" extension.
this->SourceFileExtensions.push_back( "c" );
this->SourceFileExtensions.push_back( "C" );
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" );
this->SourceFileExtensions.push_back( "M" );
this->SourceFileExtensions.push_back( "mm" );
this->HeaderFileExtensions.push_back( "h" );
this->HeaderFileExtensions.push_back( "hh" );
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" );
this->DefineFlags = " ";
this->AddDefaultDefinitions();
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/.+-]+@)");
this->cmNamedCurly.compile("^[A-Za-z0-9/_.+-]+{");
this->StateSnapshot = this->StateSnapshot.GetState()
->CreatePolicyScopeSnapshot(this->StateSnapshot);
// Enter a policy level for this directory.
this->PushPolicy();
// push empty loop block
this->PushLoopBlockBarrier();
// By default the check is not done. It is enabled by
// cmListFileCache in the top level if necessary.
this->CheckCMP0000 = false;
#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);
this->AddDefinition("CMAKE_CURRENT_SOURCE_DIR", dir);
}
{
const char* dir = this->GetCMakeInstance()->GetHomeOutputDirectory();
this->AddDefinition("CMAKE_BINARY_DIR", dir);
this->AddDefinition("CMAKE_CURRENT_BINARY_DIR", dir);
}
}
cmMakefile::~cmMakefile()
{
cmDeleteAll(this->InstallGenerators);
cmDeleteAll(this->TestGenerators);
cmDeleteAll(this->SourceFiles);
cmDeleteAll(this->Tests);
cmDeleteAll(this->ImportedTargetsOwned);
cmDeleteAll(this->FinalPassCommands);
cmDeleteAll(this->FunctionBlockers);
cmDeleteAll(this->EvaluationFiles);
this->EvaluationFiles.clear();
this->FunctionBlockers.clear();
}
//----------------------------------------------------------------------------
void cmMakefile::IssueMessage(cmake::MessageType t,
std::string const& text) const
{
// Collect context information.
if(!this->ExecutionStatusStack.empty())
{
if((t == cmake::FATAL_ERROR) || (t == cmake::INTERNAL_ERROR))
{
this->ExecutionStatusStack.back()->SetNestedError(true);
}
this->GetCMakeInstance()->IssueMessage(t, text, this->GetBacktrace());
}
else
{
cmListFileContext lfc;
// We are not currently executing a command. Add whatever context
// information we have.
lfc.FilePath = this->GetExecutionFilePath();
if(!this->GetCMakeInstance()->GetIsInTryCompile())
{
cmOutputConverter converter(this->StateSnapshot);
lfc.FilePath = converter.Convert(lfc.FilePath, cmOutputConverter::HOME);
}
lfc.Line = 0;
this->GetCMakeInstance()->IssueMessage(t, text, lfc);
}
}
cmStringRange cmMakefile::GetIncludeDirectoriesEntries() const
{
return this->StateSnapshot.GetDirectory().GetIncludeDirectoriesEntries();
}
cmBacktraceRange cmMakefile::GetIncludeDirectoriesBacktraces() const
{
return this->StateSnapshot.GetDirectory()
.GetIncludeDirectoriesEntryBacktraces();
}
cmStringRange cmMakefile::GetCompileOptionsEntries() const
{
return this->StateSnapshot.GetDirectory().GetCompileOptionsEntries();
}
cmBacktraceRange cmMakefile::GetCompileOptionsBacktraces() const
{
return this->StateSnapshot.GetDirectory().GetCompileOptionsEntryBacktraces();
}
cmStringRange cmMakefile::GetCompileDefinitionsEntries() const
{
return this->StateSnapshot.GetDirectory().GetCompileDefinitionsEntries();
}
cmBacktraceRange cmMakefile::GetCompileDefinitionsBacktraces() const
{
return this->StateSnapshot.GetDirectory()
.GetCompileDefinitionsEntryBacktraces();
}
//----------------------------------------------------------------------------
cmListFileBacktrace cmMakefile::GetBacktrace() const
{
cmListFileBacktrace backtrace;
if (!this->ContextStack.empty())
{
backtrace = cmListFileBacktrace(this->StateSnapshot,
*this->ContextStack.back());
}
return backtrace;
}
//----------------------------------------------------------------------------
cmListFileBacktrace
cmMakefile::GetBacktrace(cmCommandContext const& cc) const
{
cmState::Snapshot snp = this->StateSnapshot;
return cmListFileBacktrace(snp, cc);
}
//----------------------------------------------------------------------------
cmListFileContext cmMakefile::GetExecutionContext() const
{
return cmListFileContext::FromCommandContext(
*this->ContextStack.back(),
this->StateSnapshot.GetExecutionListFile());
}
//----------------------------------------------------------------------------
void cmMakefile::PrintCommandTrace(const cmListFileFunction& lff) const
{
std::ostringstream msg;
msg << this->GetExecutionFilePath() << "(" << lff.Line << "): ";
msg << lff.Name << "(";
bool expand = this->GetCMakeInstance()->GetTraceExpand();
std::string temp;
for(std::vector<cmListFileArgument>::const_iterator i =
lff.Arguments.begin(); i != lff.Arguments.end(); ++i)
{
if (expand)
{
temp = i->Value;
this->ExpandVariablesInString(temp);
msg << temp;
}
else
{
msg << i->Value;
}
msg << " ";
}
msg << ")";
cmSystemTools::Message(msg.str().c_str());
}
//----------------------------------------------------------------------------
bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
cmExecutionStatus &status)
{
bool result = true;
// quick return if blocked
if(this->IsFunctionBlocked(lff,status))
{
// No error.
return result;
}
std::string name = lff.Name;
// Place this call on the call stack.
cmMakefileCall stack_manager(this, lff, status);
static_cast<void>(stack_manager);
// Lookup the command prototype.
if(cmCommand* proto = this->GetState()->GetCommand(name))
{
// Clone the prototype.
cmsys::auto_ptr<cmCommand> pcmd(proto->Clone());
pcmd->SetMakefile(this);
// Decide whether to invoke the command.
if(pcmd->GetEnabled() && !cmSystemTools::GetFatalErrorOccured() &&
(this->GetCMakeInstance()->GetWorkingMode() != cmake::SCRIPT_MODE
|| pcmd->IsScriptable()))
{
// if trace is enabled, print out invoke information
if(this->GetCMakeInstance()->GetTrace())
{
this->PrintCommandTrace(lff);
}
// Try invoking the command.
if(!pcmd->InvokeInitialPass(lff.Arguments,status) ||
status.GetNestedError())
{
if(!status.GetNestedError())
{
// The command invocation requested that we report an error.
this->IssueMessage(cmake::FATAL_ERROR, pcmd->GetError());
}
result = false;
if ( this->GetCMakeInstance()->GetWorkingMode() != cmake::NORMAL_MODE)
{
cmSystemTools::SetFatalErrorOccured();
}
}
else if(pcmd->HasFinalPass())
{
// use the command
this->FinalPassCommands.push_back(pcmd.release());
}
}
else if ( this->GetCMakeInstance()->GetWorkingMode() == cmake::SCRIPT_MODE
&& !pcmd->IsScriptable() )
{
std::string error = "Command ";
error += pcmd->GetName();
error += "() is not scriptable";
this->IssueMessage(cmake::FATAL_ERROR, error);
result = false;
cmSystemTools::SetFatalErrorOccured();
}
}
else
{
if(!cmSystemTools::GetFatalErrorOccured())
{
std::string error = "Unknown CMake command \"";
error += lff.Name;
error += "\".";
this->IssueMessage(cmake::FATAL_ERROR, error);
result = false;
cmSystemTools::SetFatalErrorOccured();
}
}
return result;
}
//----------------------------------------------------------------------------
class cmMakefile::IncludeScope
{
public:
IncludeScope(cmMakefile* mf, std::string const& filenametoread,
bool noPolicyScope);
~IncludeScope();
void Quiet() { this->ReportError = false; }
private:
cmMakefile* Makefile;
bool NoPolicyScope;
bool CheckCMP0011;
bool ReportError;
void EnforceCMP0011();
};
//----------------------------------------------------------------------------
cmMakefile::IncludeScope::IncludeScope(cmMakefile* mf,
std::string const& filenametoread,
bool noPolicyScope):
Makefile(mf), NoPolicyScope(noPolicyScope),
CheckCMP0011(false), ReportError(true)
{
this->Makefile->PushFunctionBlockerBarrier();
this->Makefile->StateSnapshot =
this->Makefile->GetState()->CreateCallStackSnapshot(
this->Makefile->StateSnapshot,
this->Makefile->ContextStack.back()->Name,
this->Makefile->ContextStack.back()->Line,
filenametoread);
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;
}
}
}
//----------------------------------------------------------------------------
cmMakefile::IncludeScope::~IncludeScope()
{
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.
if(this->CheckCMP0011
&& !this->Makefile->StateSnapshot.HasDefinedPolicyCMP0011())
{
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();
}
}
this->Makefile->PopPolicyBarrier(this->ReportError);
this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
}
//----------------------------------------------------------------------------
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.
{
std::ostringstream w;
w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0011) << "\n"
<< "The included script\n "
<< this->Makefile->GetExecutionFilePath() << "\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:
{
std::ostringstream e;
e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0011) << "\n"
<< "The included script\n "
<< this->Makefile->GetExecutionFilePath() << "\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;
}
}
class cmParseFileScope
{
public:
cmParseFileScope(cmMakefile* mf)
: Makefile(mf)
{
this->Makefile->ContextStack.push_back(&this->Context);
}
~cmParseFileScope()
{
this->Makefile->ContextStack.pop_back();
}
private:
cmMakefile* Makefile;
cmCommandContext Context;
};
bool cmMakefile::ReadDependentFile(const char* filename, bool noPolicyScope)
{
this->AddDefinition("CMAKE_PARENT_LIST_FILE",
this->GetDefinition("CMAKE_CURRENT_LIST_FILE"));
std::string filenametoread =
cmSystemTools::CollapseFullPath(filename,
this->GetCurrentSourceDirectory());
IncludeScope incScope(this, filenametoread, noPolicyScope);
cmListFile listFile;
{
cmParseFileScope pfs(this);
if (!listFile.ParseFile(filenametoread.c_str(), false, this))
{
return false;
}
}
this->ReadListFile(listFile, filenametoread);
if(cmSystemTools::GetFatalErrorOccured())
{
incScope.Quiet();
}
return true;
}
class cmMakefile::ListFileScope
{
public:
ListFileScope(cmMakefile* mf, std::string const& filenametoread)
: Makefile(mf), ReportError(true)
{
long line = 0;
std::string name;
if (!this->Makefile->ContextStack.empty())
{
line = this->Makefile->ContextStack.back()->Line;
name = this->Makefile->ContextStack.back()->Name;
}
this->Makefile->StateSnapshot =
this->Makefile->GetState()->CreateInlineListFileSnapshot(
this->Makefile->StateSnapshot, name, line, filenametoread);
assert(this->Makefile->StateSnapshot.IsValid());
this->Makefile->PushFunctionBlockerBarrier();
}
~ListFileScope()
{
this->Makefile->PopPolicyBarrier(this->ReportError);
this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
}
void Quiet() { this->ReportError = false; }
private:
cmMakefile* Makefile;
bool ReportError;
};
bool cmMakefile::ReadListFile(const char* filename)
{
std::string filenametoread =
cmSystemTools::CollapseFullPath(filename,
this->GetCurrentSourceDirectory());
ListFileScope scope(this, filenametoread);
cmListFile listFile;
{
cmParseFileScope pfs(this);
if (!listFile.ParseFile(filenametoread.c_str(), false, this))
{
return false;
}
}
this->ReadListFile(listFile, filenametoread);
if(cmSystemTools::GetFatalErrorOccured())
{
scope.Quiet();
}
return true;
}
void cmMakefile::ReadListFile(cmListFile const& listFile,
std::string const& filenametoread)
{
// add this list file to the list of dependencies
this->ListFiles.push_back(filenametoread);
std::string currentParentFile
= this->GetSafeDefinition("CMAKE_PARENT_LIST_FILE");
std::string currentFile
= this->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE");
this->AddDefinition("CMAKE_CURRENT_LIST_FILE", filenametoread.c_str());
this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
cmSystemTools::GetFilenamePath(filenametoread).c_str());
this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
// Run the parsed commands.
const size_t numberFunctions = listFile.Functions.size();
for(size_t i =0; i < numberFunctions; ++i)
{
cmExecutionStatus status;
this->ExecuteCommand(listFile.Functions[i],status);
if(cmSystemTools::GetFatalErrorOccured())
{
break;
}
if(status.GetReturnInvoked())
{
// Exit early due to return command.
break;
}
}
this->CheckForUnusedVariables();
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");
}
//----------------------------------------------------------------------------
void cmMakefile::EnforceDirectoryLevelRules() const
{
// Diagnose a violation of CMP0000 if necessary.
if(this->CheckCMP0000)
{
std::ostringstream msg;
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.
this->IssueMessage(cmake::AUTHOR_WARNING, msg.str());
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.
this->IssueMessage(cmake::FATAL_ERROR, msg.str());
cmSystemTools::SetFatalErrorOccured();
return;
}
}
}
void cmMakefile::AddEvaluationFile(const std::string& inputFile,
cmsys::auto_ptr<cmCompiledGeneratorExpression> outputName,
cmsys::auto_ptr<cmCompiledGeneratorExpression> condition,
bool inputIsContent)
{
this->EvaluationFiles.push_back(
new cmGeneratorExpressionEvaluationFile(inputFile, outputName,
condition,
inputIsContent));
}
std::vector<cmGeneratorExpressionEvaluationFile*>
cmMakefile::GetEvaluationFiles() const
{
return this->EvaluationFiles;
}
namespace
{
struct file_not_persistent
{
bool operator()(const std::string& path) const
{
return !(path.find("CMakeTmp") == path.npos &&
cmSystemTools::FileExists(path.c_str()));
}
};
}
void cmMakefile::FinalPass()
{
// do all the variable expansions here
this->ExpandVariablesCMP0019();
// give all the commands a chance to do something
// after the file has been parsed before generation
for(std::vector<cmCommand*>::iterator i = this->FinalPassCommands.begin();
i != this->FinalPassCommands.end(); ++i)
{
(*i)->FinalPass();
}
//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
std::vector<std::string>::iterator new_output_files_end = std::remove_if(
this->OutputFiles.begin(),
this->OutputFiles.end(),
file_not_persistent() );
//we just have to erase all items at the back
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() );
this->ListFiles.erase(new_list_files_end, this->ListFiles.end() );
}
// Generate the output file
void cmMakefile::ConfigureFinalPass()
{
this->FinalPass();
const char* oldValue
= this->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
if (oldValue && cmSystemTools::VersionCompare(
cmSystemTools::OP_LESS, oldValue, "2.4"))
{
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.");
}
for (cmTargets::iterator l = this->Targets.begin();
l != this->Targets.end(); l++)
{
if (l->second.GetType() == cmTarget::INTERFACE_LIBRARY)
{
continue;
}
l->second.FinishConfigure();
}
}
//----------------------------------------------------------------------------
void
cmMakefile::AddCustomCommandToTarget(const std::string& target,
const std::vector<std::string>& byproducts,
const std::vector<std::string>& depends,
const cmCustomCommandLines& commandLines,
cmTarget::CustomCommandType type,
const char* comment,
const char* workingDir,
bool escapeOldStyle,
bool uses_terminal)
{
// Find the target to which to add the custom command.
cmTargets::iterator ti = this->Targets.find(target);
if(ti == this->Targets.end())
{
cmake::MessageType messageType = cmake::AUTHOR_WARNING;
bool issueMessage = false;
std::ostringstream e;
switch(this->GetPolicyStatus(cmPolicies::CMP0040))
{
case cmPolicies::WARN:
e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0040) << "\n";
issueMessage = true;
case cmPolicies::OLD:
break;
case cmPolicies::NEW:
case cmPolicies::REQUIRED_IF_USED:
case cmPolicies::REQUIRED_ALWAYS:
issueMessage = true;
messageType = cmake::FATAL_ERROR;
}
if(issueMessage)
{
e << "The target name \"" << target << "\" is unknown in this context.";
IssueMessage(messageType, e.str());
}
return;
}
if(ti->second.GetType() == cmTarget::OBJECT_LIBRARY)
{
std::ostringstream e;
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;
}
if(ti->second.GetType() == cmTarget::INTERFACE_LIBRARY)
{
std::ostringstream e;
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;
}
// 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");
}
}
// Add the command to the appropriate build step for the target.
std::vector<std::string> no_output;
cmCustomCommand cc(this, no_output, byproducts, depends,
commandLines, comment, workingDir);
cc.SetEscapeOldStyle(escapeOldStyle);
cc.SetEscapeAllowMakeVars(true);
cc.SetUsesTerminal(uses_terminal);
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;
}
}
//----------------------------------------------------------------------------
cmSourceFile*
cmMakefile::AddCustomCommandToOutput(const std::vector<std::string>& outputs,
const std::vector<std::string>& byproducts,
const std::vector<std::string>& depends,
const std::string& main_dependency,
const cmCustomCommandLines& commandLines,
const char* comment,
const char* workingDir,
bool replace,
bool escapeOldStyle,
bool uses_terminal)
{
// Make sure there is at least one output.
if(outputs.empty())
{
cmSystemTools::Error("Attempt to add a custom rule with no output!");
return 0;
}
// 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] == '"')
{
std::ostringstream e;
e << "COMMAND may not contain literal quotes:\n " << cl[0] << "\n";
this->IssueMessage(cmake::FATAL_ERROR, e.str());
return 0;
}
}
// Choose a source file on which to store the custom command.
cmSourceFile* file = 0;
if(!commandLines.empty() && !main_dependency.empty())
{
// 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)
{
// The main dependency already has a custom command.
if(commandLines == file->GetCustomCommand()->GetCommandLines())
{
// The existing custom command is identical. Silently ignore
// the duplicate.
return file;
}
else
{
// The existing custom command is different. We need to
// generate a rule file for this new command.
file = 0;
}
}
else if (!file)
{
file = this->CreateSource(main_dependency);
}
}
// Generate a rule file if the main dependency is not available.
if(!file)
{
cmGlobalGenerator* gg = this->GetGlobalGenerator();
// Construct a rule file associated with the first output produced.
std::string outName = gg->GenerateRuleFile(outputs[0]);
// Check if the rule file already exists.
file = this->GetSource(outName);
if(file && file->GetCustomCommand() && !replace)
{
// The rule file already exists.
if(commandLines != file->GetCustomCommand()->GetCommandLines())
{
cmSystemTools::Error("Attempt to add a custom rule to output \"",
outName.c_str(),
"\" which already has a custom rule.");
}
return file;
}
// Create a cmSourceFile for the rule file.
if (!file)
{
file = this->CreateSource(outName, true);
}
file->SetProperty("__CMAKE_RULE", "1");
}
// Always create the output sources and mark them generated.
for(std::vector<std::string>::const_iterator o = outputs.begin();
o != outputs.end(); ++o)
{
if(cmSourceFile* out = this->GetOrCreateSource(*o, true))
{
out->SetProperty("GENERATED", "1");
}
}
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");
}
}
// Attach the custom command to the file.
if(file)
{
// Construct a complete list of dependencies.
std::vector<std::string> depends2(depends);
if(!main_dependency.empty())
{
depends2.push_back(main_dependency);
}
cmCustomCommand* cc =
new cmCustomCommand(this, outputs, byproducts, depends2,
commandLines, comment, workingDir);
cc->SetEscapeOldStyle(escapeOldStyle);
cc->SetEscapeAllowMakeVars(true);
cc->SetUsesTerminal(uses_terminal);
file->SetCustomCommand(cc);
this->UpdateOutputToSourceMap(outputs, file);
}
return file;
}
//----------------------------------------------------------------------------
void
cmMakefile::UpdateOutputToSourceMap(std::vector<std::string> const& outputs,
cmSourceFile* source)
{
for(std::vector<std::string>::const_iterator o = outputs.begin();
o != outputs.end(); ++o)
{
this->UpdateOutputToSourceMap(*o, source);
}
}
//----------------------------------------------------------------------------
void
cmMakefile::UpdateOutputToSourceMap(std::string const& output,
cmSourceFile* source)
{
OutputToSourceMap::iterator i = this->OutputToSource.find(output);
if(i != this->OutputToSource.end())
{
// Multiple custom commands produce the same output but may
// be attached to a different source file (MAIN_DEPENDENCY).
// LinearGetSourceFileWithOutput would return the first one,
// so keep the mapping for the first one.
//
// TODO: Warn the user about this case. However, the VS 8 generator
// triggers it for separate generate.stamp rules in ZERO_CHECK and
// individual targets.
return;
}
this->OutputToSource[output] = source;
}
//----------------------------------------------------------------------------
cmSourceFile*
cmMakefile::AddCustomCommandToOutput(const std::string& output,
const std::vector<std::string>& depends,
const std::string& main_dependency,
const cmCustomCommandLines& commandLines,
const char* comment,
const char* workingDir,
bool replace,
bool escapeOldStyle,
bool uses_terminal)
{
std::vector<std::string> outputs;
outputs.push_back(output);
std::vector<std::string> no_byproducts;
return this->AddCustomCommandToOutput(outputs, no_byproducts,
depends, main_dependency,
commandLines, comment, workingDir,
replace, escapeOldStyle,
uses_terminal);
}
//----------------------------------------------------------------------------
void
cmMakefile::AddCustomCommandOldStyle(const std::string& target,
const std::vector<std::string>& outputs,
const std::vector<std::string>& depends,
const std::string& source,
const cmCustomCommandLines& commandLines,
const char* comment)
{
// Translate the old-style signature to one of the new-style
// signatures.
if(source == target)
{
// In the old-style signature if the source and target were the
// same then it added a post-build rule to the target. Preserve
// this behavior.
std::vector<std::string> no_byproducts;
this->AddCustomCommandToTarget(target, no_byproducts,
depends, commandLines,
cmTarget::POST_BUILD, comment, 0);
return;
}
// Each output must get its own copy of this rule.
cmsys::RegularExpression sourceFiles("\\.(C|M|c|c\\+\\+|cc|cpp|cxx|m|mm|"
"rc|def|r|odl|idl|hpj|bat|h|h\\+\\+|"
"hm|hpp|hxx|in|txx|inl)$");
for(std::vector<std::string>::const_iterator oi = outputs.begin();
oi != outputs.end(); ++oi)
{
// Get the name of this output.
const char* output = oi->c_str();
cmSourceFile* sf;
// Choose whether to use a main dependency.
if(sourceFiles.find(source))
{
// The source looks like a real file. Use it as the main dependency.
sf = this->AddCustomCommandToOutput(output, depends, source,
commandLines, comment, 0);
}
else
{
// The source may not be a real file. Do not use a main dependency.
std::string no_main_dependency = "";
std::vector<std::string> depends2 = depends;
depends2.push_back(source);
sf = this->AddCustomCommandToOutput(output, depends2, no_main_dependency,
commandLines, comment, 0);
}
// If the rule was added to the source (and not a .rule file),
// then add the source to the target to make sure the rule is
// included.
if(sf && !sf->GetPropertyAsBool("__CMAKE_RULE"))
{
if (this->Targets.find(target) != this->Targets.end())
{
this->Targets[target].AddSource(sf->GetFullPath());
}
else
{
cmSystemTools::Error("Attempt to add a custom rule to a target "
"that does not exist yet for target ",
target.c_str());
return;
}
}
}
}
//----------------------------------------------------------------------------
cmTarget*
cmMakefile::AddUtilityCommand(const std::string& utilityName,
bool excludeFromAll,
const std::vector<std::string>& depends,
const char* workingDirectory,
const char* command,
const char* arg1,
const char* arg2,
const char* arg3,
const char* arg4)
{
// Construct the command line for the custom command.
cmCustomCommandLine commandLine;
commandLine.push_back(command);
if(arg1)
{
commandLine.push_back(arg1);
}
if(arg2)
{
commandLine.push_back(arg2);
}
if(arg3)
{
commandLine.push_back(arg3);
}
if(arg4)
{
commandLine.push_back(arg4);
}
cmCustomCommandLines commandLines;
commandLines.push_back(commandLine);
// Call the real signature of this method.
return this->AddUtilityCommand(utilityName, excludeFromAll, workingDirectory,
depends, commandLines);
}
//----------------------------------------------------------------------------
cmTarget*
cmMakefile::AddUtilityCommand(const std::string& utilityName,
bool excludeFromAll,
const char* workingDirectory,
const std::vector<std::string>& depends,
const cmCustomCommandLines& commandLines,
bool escapeOldStyle, const char* comment,
bool uses_terminal)
{
std::vector<std::string> no_byproducts;
return this->AddUtilityCommand(utilityName, excludeFromAll, workingDirectory,
no_byproducts, depends, commandLines,
escapeOldStyle, comment, uses_terminal);
}
//----------------------------------------------------------------------------
cmTarget*
cmMakefile::AddUtilityCommand(const std::string& utilityName,
bool excludeFromAll,
const char* workingDirectory,
const std::vector<std::string>& byproducts,
const std::vector<std::string>& depends,
const cmCustomCommandLines& commandLines,
bool escapeOldStyle, const char* comment,
bool uses_terminal)
{
// Create a target instance for this utility.
cmTarget* target = this->AddNewTarget(cmTarget::UTILITY, utilityName);
if (excludeFromAll)
{
target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
}
if(!comment)
{
// Use an empty comment to avoid generation of default comment.
comment = "";
}
// Store the custom command in the target.
if (!commandLines.empty() || !depends.empty())
{
std::string force = this->GetCurrentBinaryDirectory();
force += cmake::GetCMakeFilesDirectory();
force += "/";
force += utilityName;
std::vector<std::string> forced;
forced.push_back(force);
std::string no_main_dependency = "";
bool no_replace = false;
this->AddCustomCommandToOutput(forced, byproducts,
depends, no_main_dependency,
commandLines, comment,
workingDirectory, no_replace,
escapeOldStyle, uses_terminal);
cmSourceFile* sf = target->AddSourceCMP0049(force);
// The output is not actually created so mark it symbolic.
if(sf)
{
sf->SetProperty("SYMBOLIC", "1");
}
else
{
cmSystemTools::Error("Could not get source file entry for ",
force.c_str());
}
// 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");
}
}
}
return target;
}
void cmMakefile::AddDefineFlag(const char* flag)
{
if (!flag)
{
return;
}
// Update the string used for the old DEFINITIONS property.
this->AddDefineFlag(flag, this->DefineFlagsOrig);
// If this is really a definition, update COMPILE_DEFINITIONS.
if(this->ParseDefineFlag(flag, false))
{
return;
}
// Add this flag that does not look like a definition.
this->AddDefineFlag(flag, this->DefineFlags);
}
void cmMakefile::AddDefineFlag(const char* flag, std::string& dflags)
{
// remove any \n\r
std::string::size_type initSize = dflags.size();
dflags += std::string(" ") + flag;
std::string::iterator flagStart = dflags.begin() + initSize + 1;
std::replace(flagStart, dflags.end(), '\n', ' ');
std::replace(flagStart, dflags.end(), '\r', ' ');
}
void cmMakefile::RemoveDefineFlag(const char* flag)
{
// Check the length of the flag to remove.
std::string::size_type len = strlen(flag);
if(len < 1)
{
return;
}
// Update the string used for the old DEFINITIONS property.
this->RemoveDefineFlag(flag, len, this->DefineFlagsOrig);
// If this is really a definition, update COMPILE_DEFINITIONS.
if(this->ParseDefineFlag(flag, true))
{
return;
}
// Remove this flag that does not look like a definition.
this->RemoveDefineFlag(flag, len, this->DefineFlags);
}
void cmMakefile::RemoveDefineFlag(const char* flag,
std::string::size_type len,
std::string& dflags)
{
// Remove all instances of the flag that are surrounded by
// whitespace or the beginning/end of the string.
for(std::string::size_type lpos = dflags.find(flag, 0);
lpos != std::string::npos; lpos = dflags.find(flag, lpos))
{
std::string::size_type rpos = lpos + len;
if((lpos <= 0 || isspace(dflags[lpos-1])) &&
(rpos >= dflags.size() || isspace(dflags[rpos])))
{
dflags.erase(lpos, len);
}
else
{
++lpos;
}
}
}
void cmMakefile::AddCompileOption(const char* option)
{
this->AppendProperty("COMPILE_OPTIONS", option);
}
bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
{
// Create a regular expression to match valid definitions.
static cmsys::RegularExpression
valid("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=.*)?$");
// Make sure the definition matches.
if(!valid.find(def.c_str()))
{
return false;
}
// VS6 IDE does not support definition values with spaces in
// combination with '"', '$', or ';'.
if((this->GetGlobalGenerator()->GetName() == "Visual Studio 6") &&
(def.find(" ") != def.npos && def.find_first_of("\"$;") != def.npos))
{
return false;
}
// Definitions with non-trivial values require a policy check.
static cmsys::RegularExpression
trivial("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=[A-Za-z0-9_.]+)?$");
if(!trivial.find(def.c_str()))
{
// This definition has a non-trivial value.
switch(this->GetPolicyStatus(cmPolicies::CMP0005))
{
case cmPolicies::WARN:
this->IssueMessage(
cmake::AUTHOR_WARNING,
cmPolicies::GetPolicyWarning(cmPolicies::CMP0005)
);
case cmPolicies::OLD:
// OLD behavior is to not escape the value. We should not
// convert the definition to use the property.
return false;
case cmPolicies::REQUIRED_IF_USED:
case cmPolicies::REQUIRED_ALWAYS:
this->IssueMessage(
cmake::FATAL_ERROR,
cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0005)
);
return false;
case cmPolicies::NEW:
// NEW behavior is to escape the value. Proceed to convert it
// to an entry in the property.
break;
}
}
// Get the definition part after the flag.
const char* define = def.c_str() + 2;
if(remove)
{
if(const char* cdefs = this->GetProperty("COMPILE_DEFINITIONS"))
{
// Expand the list.
std::vector<std::string> defs;
cmSystemTools::ExpandListArgument(cdefs, defs);
// Recompose the list without the definition.
std::vector<std::string>::const_iterator defEnd =
std::remove(defs.begin(), defs.end(), define);
std::vector<std::string>::const_iterator defBegin =
defs.begin();
std::string ndefs = cmJoin(cmMakeRange(defBegin, defEnd), ";");
// Store the new list.
this->SetProperty("COMPILE_DEFINITIONS", ndefs.c_str());
}
}
else
{
// Append the definition to the directory property.
this->AppendProperty("COMPILE_DEFINITIONS", define);
}
return true;
}
void cmMakefile::AddLinkLibrary(const std::string& lib,
cmTarget::LinkLibraryType llt)
{
cmTarget::LibraryID tmp;
tmp.first = lib;
tmp.second = llt;
this->LinkLibraries.push_back(tmp);
}
void cmMakefile::AddLinkLibraryForTarget(const std::string& target,
const std::string& lib,
cmTarget::LinkLibraryType llt)
{
cmTargets::iterator i = this->Targets.find(target);
if ( i != this->Targets.end())
{
cmTarget* tgt = this->GetGlobalGenerator()->FindTarget(lib);
if(tgt)
{
// if it is not a static or shared library then you can not link to it
if(!((tgt->GetType() == cmTarget::STATIC_LIBRARY) ||
(tgt->GetType() == cmTarget::SHARED_LIBRARY) ||
(tgt->GetType() == cmTarget::INTERFACE_LIBRARY) ||
tgt->IsExecutableWithExports()))
{
std::ostringstream e;
e << "Target \"" << lib << "\" of type "
<< cmTarget::GetTargetTypeName(tgt->GetType())
<< " may not be linked into another target. "
<< "One may link only to STATIC or SHARED libraries, or "
<< "to executables with the ENABLE_EXPORTS property set.";
this->IssueMessage(cmake::FATAL_ERROR, e.str());
}
}
i->second.AddLinkLibrary( *this, target, lib, llt );
}
else
{
std::ostringstream e;
e << "Attempt to add link library \""
<< lib << "\" to target \""
<< target << "\" which is not built in this directory.";
this->IssueMessage(cmake::FATAL_ERROR, e.str());
}
}
void cmMakefile::AddLinkDirectoryForTarget(const std::string& target,
const std::string& d)
{
cmTargets::iterator i = this->Targets.find(target);
if ( i != this->Targets.end())
{
if(this->IsAlias(target))
{
std::ostringstream e;
e << "ALIAS target \"" << target << "\" "
<< "may not be linked into another target.";
this->IssueMessage(cmake::FATAL_ERROR, e.str());
return;
}
i->second.AddLinkDirectory( d );
}
else
{
cmSystemTools::Error
("Attempt to add link directories to non-existent target: ",
target.c_str(), " for directory ", d.c_str());
}
}
void cmMakefile::AddLinkLibrary(const std::string& lib)
{
this->AddLinkLibrary(lib,cmTarget::GENERAL);
}
void cmMakefile::InitializeFromParent(cmMakefile* parent)
{
this->StateSnapshot.InitializeFromParent();
this->AddDefinition("CMAKE_CURRENT_SOURCE_DIR",
this->GetCurrentSourceDirectory());
this->AddDefinition("CMAKE_CURRENT_BINARY_DIR",
this->GetCurrentBinaryDirectory());
this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
// define flags
this->DefineFlags = parent->DefineFlags;
this->DefineFlagsOrig = parent->DefineFlagsOrig;
// Include transform property. There is no per-config version.
{
const char* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
this->SetProperty(prop, parent->GetProperty(prop));
}
// compile definitions property and per-config versions
cmPolicies::PolicyStatus polSt = this->GetPolicyStatus(cmPolicies::CMP0043);
if (polSt == cmPolicies::WARN || polSt == cmPolicies::OLD)
{
this->SetProperty("COMPILE_DEFINITIONS",
parent->GetProperty("COMPILE_DEFINITIONS"));
std::vector<std::string> configs;
this->GetConfigurations(configs);
for(std::vector<std::string>::const_iterator ci = configs.begin();
ci != configs.end(); ++ci)
{
std::string defPropName = "COMPILE_DEFINITIONS_";
defPropName += cmSystemTools::UpperCase(*ci);
const char* prop = parent->GetProperty(defPropName);
this->SetProperty(defPropName, prop);
}
}
// link libraries
this->LinkLibraries = parent->LinkLibraries;
// link directories
this->SetProperty("LINK_DIRECTORIES",
parent->GetProperty("LINK_DIRECTORIES"));
// the initial project name
this->SetProjectName(parent->GetProjectName());
// Copy include regular expressions.
this->ComplainFileRegularExpression = parent->ComplainFileRegularExpression;
// Imported targets.
this->ImportedTargets = parent->ImportedTargets;
}
void cmMakefile::PushFunctionScope(std::string const& fileName,
const cmPolicies::PolicyMap& pm)
{
this->StateSnapshot =
this->GetState()->CreateFunctionCallSnapshot(
this->StateSnapshot,
this->ContextStack.back()->Name, this->ContextStack.back()->Line,
fileName);
assert(this->StateSnapshot.IsValid());
this->PushLoopBlockBarrier();
#if defined(CMAKE_BUILD_WITH_CMAKE)
this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
#endif
this->PushFunctionBlockerBarrier();
this->PushPolicy(true, pm);
}
void cmMakefile::PopFunctionScope(bool reportError)
{
this->PopPolicy();
this->PopPolicyBarrier(reportError);
this->PopFunctionBlockerBarrier(reportError);
#if defined(CMAKE_BUILD_WITH_CMAKE)
this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
#endif
this->PopLoopBlockBarrier();
this->CheckForUnusedVariables();
}
void cmMakefile::PushMacroScope(std::string const& fileName,
const cmPolicies::PolicyMap& pm)
{
this->StateSnapshot =
this->GetState()->CreateMacroCallSnapshot(
this->StateSnapshot,
this->ContextStack.back()->Name, this->ContextStack.back()->Line,
fileName);
assert(this->StateSnapshot.IsValid());
this->PushFunctionBlockerBarrier();
this->PushPolicy(true, pm);
}
void cmMakefile::PopMacroScope(bool reportError)
{
this->PopPolicy();
this->PopPolicyBarrier(reportError);
this->PopFunctionBlockerBarrier(reportError);
}
bool cmMakefile::IsRootMakefile() const
{
return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
}
class cmMakefile::BuildsystemFileScope
{
public:
BuildsystemFileScope(cmMakefile* mf)
: Makefile(mf), ReportError(true)
{
std::string currentStart =
this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource();
currentStart += "/CMakeLists.txt";
this->Makefile->StateSnapshot.SetListFile(currentStart);
this->Makefile->StateSnapshot = this->Makefile->StateSnapshot.GetState()
->CreatePolicyScopeSnapshot(this->Makefile->StateSnapshot);
this->Makefile->PushFunctionBlockerBarrier();
this->GG = mf->GetGlobalGenerator();
this->CurrentMakefile = this->GG->GetCurrentMakefile();
this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot();
this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
this->GG->SetCurrentMakefile(mf);
#if defined(CMAKE_BUILD_WITH_CMAKE)
this->GG->GetFileLockPool().PushFileScope();
#endif
}
~BuildsystemFileScope()
{
this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
this->Makefile->PopPolicyBarrier(this->ReportError);
#if defined(CMAKE_BUILD_WITH_CMAKE)
this->GG->GetFileLockPool().PopFileScope();
#endif
this->GG->SetCurrentMakefile(this->CurrentMakefile);
this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
}
void Quiet() { this->ReportError = false; }
private:
cmMakefile* Makefile;
cmGlobalGenerator* GG;
cmMakefile* CurrentMakefile;
cmState::Snapshot Snapshot;
bool ReportError;
};
//----------------------------------------------------------------------------
void cmMakefile::Configure()
{
BuildsystemFileScope scope(this);
// make sure the CMakeFiles dir is there
std::string filesDir = this->StateSnapshot.GetDirectory().GetCurrentBinary();
filesDir += cmake::GetCMakeFilesDirectory();
cmSystemTools::MakeDirectory(filesDir.c_str());
std::string currentStart =
this->StateSnapshot.GetDirectory().GetCurrentSource();
currentStart += "/CMakeLists.txt";
assert(cmSystemTools::FileExists(currentStart.c_str(), true));
this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentStart.c_str());
cmListFile listFile;
{
cmParseFileScope pfs(this);
if (!listFile.ParseFile(currentStart.c_str(), this->IsRootMakefile(), this))
{
return;
}
}
this->ReadListFile(listFile, currentStart);
if(cmSystemTools::GetFatalErrorOccured())
{
scope.Quiet();
}
// at the end handle any old style subdirs
std::vector<cmMakefile*> subdirs = this->UnConfiguredDirectories;
// for each subdir recurse
std::vector<cmMakefile*>::iterator sdi = subdirs.begin();
for (; sdi != subdirs.end(); ++sdi)
{
this->ConfigureSubDirectory(*sdi);
}
this->AddCMakeDependFilesFromUser();
}
void cmMakefile::ConfigureSubDirectory(cmMakefile *mf)
{
mf->InitializeFromParent(this);
std::string currentStart = mf->GetCurrentSourceDirectory();
if (this->GetCMakeInstance()->GetDebugOutput())
{
std::string msg=" Entering ";
msg += currentStart;
cmSystemTools::Message(msg.c_str());
}
std::string const currentStartFile = currentStart + "/CMakeLists.txt";
if (!cmSystemTools::FileExists(currentStartFile, true))
{
// The file is missing. Check policy CMP0014.
std::ostringstream e;
e << "The source directory\n"
<< " " << currentStart << "\n"
<< "does not contain a CMakeLists.txt file.";
switch (this->GetPolicyStatus(cmPolicies::CMP0014))
{
case cmPolicies::WARN:
// Print the warning.
e << "\n"
<< "CMake does not support this case but it used "
<< "to work accidentally and is being allowed for "
<< "compatibility."
<< "\n"
<< cmPolicies::GetPolicyWarning(cmPolicies::CMP0014);
this->IssueMessage(cmake::AUTHOR_WARNING, e.str());
case cmPolicies::OLD:
// OLD behavior does not warn.
break;
case cmPolicies::REQUIRED_IF_USED:
case cmPolicies::REQUIRED_ALWAYS:
e << "\n"
<< cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0014);
case cmPolicies::NEW:
// NEW behavior prints the error.
this->IssueMessage(cmake::FATAL_ERROR, e.str());
}
return;
}
// finally configure the subdir
mf->Configure();
if (this->GetCMakeInstance()->GetDebugOutput())
{
std::string msg=" Returning to ";
msg += this->GetCurrentSourceDirectory();
cmSystemTools::Message(msg.c_str());
}
}
void cmMakefile::AddSubDirectory(const std::string& srcPath,
const std::string& binPath,
bool excludeFromAll,
bool immediate)
{
// Make sure the binary directory is unique.
if(!this->EnforceUniqueDir(srcPath, binPath))
{
return;
}
cmState::Snapshot newSnapshot = this->GetState()
->CreateBuildsystemDirectorySnapshot(this->StateSnapshot,
this->ContextStack.back()->Name,
this->ContextStack.back()->Line);
cmMakefile* subMf = new cmMakefile(this->GlobalGenerator, newSnapshot);
this->GetGlobalGenerator()->AddMakefile(subMf);
// set the subdirs start dirs
subMf->SetCurrentSourceDirectory(srcPath);
subMf->SetCurrentBinaryDirectory(binPath);
if(excludeFromAll)
{
subMf->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
}
if (immediate)
{
this->ConfigureSubDirectory(subMf);
}
else
{
this->UnConfiguredDirectories.push_back(subMf);
}
}
void cmMakefile::SetCurrentSourceDirectory(const std::string& dir)
{
this->StateSnapshot.GetDirectory().SetCurrentSource(dir);
this->AddDefinition("CMAKE_CURRENT_SOURCE_DIR",
this->StateSnapshot.GetDirectory().GetCurrentSource());
}
const char* cmMakefile::GetCurrentSourceDirectory() const
{
return this->StateSnapshot.GetDirectory().GetCurrentSource();
}
void cmMakefile::SetCurrentBinaryDirectory(const std::string& dir)
{
this->StateSnapshot.GetDirectory().SetCurrentBinary(dir);
const char* binDir = this->StateSnapshot.GetDirectory().GetCurrentBinary();
cmSystemTools::MakeDirectory(binDir);
this->AddDefinition("CMAKE_CURRENT_BINARY_DIR", binDir);
}
const char* cmMakefile::GetCurrentBinaryDirectory() const
{
return this->StateSnapshot.GetDirectory().GetCurrentBinary();
}
void cmMakefile::AddGeneratorTarget(cmTarget* t, cmGeneratorTarget* gt)
{
this->GeneratorTargets[t] = gt;
this->GetGlobalGenerator()->AddGeneratorTarget(t, gt);
}
//----------------------------------------------------------------------------
void cmMakefile::AddIncludeDirectories(const std::vector<std::string> &incs,
bool before)
{
if (incs.empty())
{
return;
}
cmListFileBacktrace lfbt = this->GetBacktrace();
std::string entryString = cmJoin(incs, ";");
if (before)
{
this->StateSnapshot.GetDirectory()
.PrependIncludeDirectoriesEntry(entryString, lfbt);
}
else
{
this->StateSnapshot.GetDirectory()
.AppendIncludeDirectoriesEntry(entryString, lfbt);
}
// Property on each target:
for (cmTargets::iterator l = this->Targets.begin();
l != this->Targets.end(); ++l)
{
cmTarget &t = l->second;
t.InsertInclude(entryString, lfbt, before);
}
}
//----------------------------------------------------------------------------
void
cmMakefile::AddSystemIncludeDirectories(const std::set<std::string> &incs)
{
this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
for (cmTargets::iterator l = this->Targets.begin();
l != this->Targets.end(); ++l)
{
cmTarget &t = l->second;
t.AddSystemIncludeDirectories(incs);
}
}
void cmMakefile::AddDefinition(const std::string& name, const char* value)
{
if (!value )
{
return;
}
if (this->VariableInitialized(name))
{
this->LogUnused("changing definition", name);
}
this->StateSnapshot.SetDefinition(name, value);
#ifdef CMAKE_BUILD_WITH_CMAKE
cmVariableWatch* vv = this->GetVariableWatch();
if ( vv )
{
vv->VariableAccessed(name,
cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
value,
this);
}
#endif
}
void cmMakefile::AddCacheDefinition(const std::string& name, const char* value,
const char* doc,
cmState::CacheEntryType type,
bool force)
{
bool haveVal = value ? true : false;
std::string val = haveVal ? value : "";
const char* existingValue =
this->GetState()->GetInitializedCacheValue(name);
if(existingValue
&& (this->GetState()->GetCacheEntryType(name)
== cmState::UNINITIALIZED))
{
// if this is not a force, then use the value from the cache
// if it is a force, then use the value being passed in
if(!force)
{
val = existingValue;
haveVal = true;
}
if ( type == cmState::PATH || type == cmState::FILEPATH )
{
std::vector<std::string>::size_type cc;
std::vector<std::string> files;
std::string nvalue = "";
cmSystemTools::ExpandListArgument(val, files);
for ( cc = 0; cc < files.size(); cc ++ )
{
if(!cmSystemTools::IsOff(files[cc].c_str()))
{
files[cc] = cmSystemTools::CollapseFullPath(files[cc]);
}
if ( cc > 0 )
{
nvalue += ";";
}
nvalue += files[cc];
}
this->GetState()->AddCacheEntry(name, nvalue.c_str(), doc, type);
val = this->GetState()->GetInitializedCacheValue(name);
haveVal = true;
}
}
this->GetState()->AddCacheEntry(name, haveVal ? val.c_str() : 0,
doc, type);
// if there was a definition then remove it
this->StateSnapshot.RemoveDefinition(name);
}
void cmMakefile::AddDefinition(const std::string& name, bool value)
{
if (this->VariableInitialized(name))
{
this->LogUnused("changing definition", name);
}
this->StateSnapshot.SetDefinition(name, value ? "ON" : "OFF");
#ifdef CMAKE_BUILD_WITH_CMAKE
cmVariableWatch* vv = this->GetVariableWatch();
if ( vv )
{
vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
value?"ON":"OFF", this);
}
#endif
}
void cmMakefile::CheckForUnusedVariables() const
{
if (!this->WarnUnused)
{
return;
}
const std::vector<std::string>& unused = this->StateSnapshot.UnusedKeys();
std::vector<std::string>::const_iterator it = unused.begin();
for (; it != unused.end(); ++it)
{
this->LogUnused("out of scope", *it);
}
}
void cmMakefile::MarkVariableAsUsed(const std::string& var)
{
this->StateSnapshot.GetDefinition(var);
}
bool cmMakefile::VariableInitialized(const std::string& var) const
{
return this->StateSnapshot.IsInitialized(var);
}
void cmMakefile::LogUnused(const char* reason,
const std::string& name) const
{
if (this->WarnUnused)
{
std::string path;
cmListFileContext lfc;
if (!this->ExecutionStatusStack.empty())
{
lfc = this->GetExecutionContext();
path = lfc.FilePath;
}
else
{
path = this->GetCurrentSourceDirectory();
path += "/CMakeLists.txt";
lfc.FilePath = path;
lfc.Line = 0;
}
cmOutputConverter converter(this->StateSnapshot);
lfc.FilePath = converter.Convert(lfc.FilePath, cmOutputConverter::HOME);
if (this->CheckSystemVars ||
cmSystemTools::IsSubDirectory(path,
this->GetHomeDirectory()) ||
(cmSystemTools::IsSubDirectory(path,
this->GetHomeOutputDirectory()) &&
!cmSystemTools::IsSubDirectory(path,
cmake::GetCMakeFilesDirectory())))
{
std::ostringstream msg;
msg << "unused variable (" << reason << ") \'" << name << "\'";
this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING,
msg.str(),
lfc);
}
}
}
void cmMakefile::RemoveDefinition(const std::string& name)
{
if (this->VariableInitialized(name))
{
this->LogUnused("unsetting", name);
}
this->StateSnapshot.RemoveDefinition(name);
#ifdef CMAKE_BUILD_WITH_CMAKE
cmVariableWatch* vv = this->GetVariableWatch();
if ( vv )
{
vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
0, this);
}
#endif
}
void cmMakefile::RemoveCacheDefinition(const std::string& name)
{
this->GetState()->RemoveCacheEntry(name);
}
void cmMakefile::SetProjectName(std::string const& p)
{
this->StateSnapshot.SetProjectName(p);
}
std::string cmMakefile::GetProjectName() const
{
return this->StateSnapshot.GetProjectName();
}
void cmMakefile::AddGlobalLinkInformation(const std::string& name,
cmTarget& target)
{
// for these targets do not add anything
switch(target.GetType())
{
case cmTarget::UTILITY:
case cmTarget::GLOBAL_TARGET:
case cmTarget::INTERFACE_LIBRARY:
return;
default:;
}
if (const char* linkDirsProp = this->GetProperty("LINK_DIRECTORIES"))
{
std::vector<std::string> linkDirs;
cmSystemTools::ExpandListArgument(linkDirsProp, linkDirs);
for(std::vector<std::string>::iterator j = linkDirs.begin();
j != linkDirs.end(); ++j)
{
std::string newdir = *j;
// remove trailing slashes
if(*j->rbegin() == '/')
{
newdir = j->substr(0, j->size()-1);
}
if(std::find(this->LinkDirectories.begin(),
this->LinkDirectories.end(), newdir)
== this->LinkDirectories.end())
{
target.AddLinkDirectory(*j);
}
}
}
target.MergeLinkLibraries( *this, name, this->LinkLibraries );
}
void cmMakefile::AddAlias(const std::string& lname, cmTarget *tgt)
{
this->AliasTargets[lname] = tgt;
this->GetGlobalGenerator()->AddAlias(lname, tgt);
}
cmTarget* cmMakefile::AddLibrary(const std::string& lname,
cmTarget::TargetType type,
const std::vector<std::string> &srcs,
bool excludeFromAll)
{
// wrong type ? default to STATIC
if ( (type != cmTarget::STATIC_LIBRARY)
&& (type != cmTarget::SHARED_LIBRARY)
&& (type != cmTarget::MODULE_LIBRARY)
&& (type != cmTarget::OBJECT_LIBRARY)
&& (type != cmTarget::INTERFACE_LIBRARY))
{
this->IssueMessage(cmake::INTERNAL_ERROR,
"cmMakefile::AddLibrary given invalid target type.");
type = cmTarget::STATIC_LIBRARY;
}
cmTarget* target = this->AddNewTarget(type, lname);
// Clear its dependencies. Otherwise, dependencies might persist
// over changes in CMakeLists.txt, making the information stale and
// hence useless.
target->ClearDependencyInformation( *this, lname );
if(excludeFromAll)
{
target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
}
target->AddSources(srcs);
this->AddGlobalLinkInformation(lname, *target);
return target;
}
cmTarget* cmMakefile::AddExecutable(const char *exeName,
const std::vector<std::string> &srcs,
bool excludeFromAll)
{
cmTarget* target = this->AddNewTarget(cmTarget::EXECUTABLE, exeName);
if(excludeFromAll)
{
target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
}
target->AddSources(srcs);
this->AddGlobalLinkInformation(exeName, *target);
return target;
}
//----------------------------------------------------------------------------
cmTarget*
cmMakefile::AddNewTarget(cmTarget::TargetType type, const std::string& name)
{
cmTargets::iterator it =
this->Targets.insert(cmTargets::value_type(name, cmTarget())).first;
cmTarget& target = it->second;
target.SetType(type, name);
target.SetMakefile(this);
this->GetGlobalGenerator()->AddTarget(&it->second);
return &it->second;
}
cmSourceFile*
cmMakefile::LinearGetSourceFileWithOutput(const std::string& name) const
{
std::string out;
// look through all the source files that have custom commands
// and see if the custom command has the passed source file as an output
for(std::vector<cmSourceFile*>::const_iterator i =
this->SourceFiles.begin(); i != this->SourceFiles.end(); ++i)
{
// does this source file have a custom command?
if ((*i)->GetCustomCommand())
{
// Does the output of the custom command match the source file name?
const std::vector<std::string>& outputs =
(*i)->GetCustomCommand()->GetOutputs();
for(std::vector<std::string>::const_iterator o = outputs.begin();
o != outputs.end(); ++o)
{
out = *o;
std::string::size_type pos = out.rfind(name);
// If the output matches exactly
if (pos != out.npos &&
pos == out.size() - name.size() &&
(pos ==0 || out[pos-1] == '/'))
{
return *i;
}
}
}
}
// otherwise return NULL
return 0;
}
cmSourceFile *cmMakefile::GetSourceFileWithOutput(
const std::string& name) const
{
// If the queried path is not absolute we use the backward compatible
// linear-time search for an output with a matching suffix.
if(!cmSystemTools::FileIsFullPath(name.c_str()))
{
return this->LinearGetSourceFileWithOutput(name);
}
// Otherwise we use an efficient lookup map.
OutputToSourceMap::const_iterator o = this->OutputToSource.find(name);
if (o != this->OutputToSource.end())
{
return (*o).second;
}
return 0;
}
#if defined(CMAKE_BUILD_WITH_CMAKE)
cmSourceGroup*
cmMakefile::GetSourceGroup(const std::vector<std::string>&name) const
{
cmSourceGroup* sg = 0;
// first look for source group starting with the same as the one we wants
for (std::vector<cmSourceGroup>::const_iterator
sgIt = this->SourceGroups.begin();
sgIt != this->SourceGroups.end(); ++sgIt)
{
std::string sgName = sgIt->GetName();
if(sgName == name[0])
{
sg = const_cast<cmSourceGroup*>(&(*sgIt));
break;
}
}
if(sg != 0)
{
// iterate through its children to find match source group
for(unsigned int i=1; i<name.size(); ++i)
{
sg = sg->LookupChild(name[i].c_str());
if(sg == 0)
{
break;
}
}
}
return sg;
}
void cmMakefile::AddSourceGroup(const std::string& name,
const char* regex)
{
std::vector<std::string> nameVector;
nameVector.push_back(name);
AddSourceGroup(nameVector, regex);
}
void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
const char* regex)
{
cmSourceGroup* sg = 0;
std::vector<std::string> currentName;
int i = 0;
const int lastElement = static_cast<int>(name.size()-1);
for(i=lastElement; i>=0; --i)
{
currentName.assign(name.begin(), name.begin()+i+1);
sg = this->GetSourceGroup(currentName);
if(sg != 0)
{
break;
}
}
// i now contains the index of the last found component
if(i==lastElement)
{
// group already exists, replace its regular expression
if ( regex && sg)
{
// We only want to set the regular expression. If there are already
// source files in the group, we don't want to remove them.
sg->SetGroupRegex(regex);
}
return;
}
else if(i==-1)
{
// group does not exist nor belong to any existing group
// add its first component
this->SourceGroups.push_back(cmSourceGroup(name[0].c_str(), regex));
sg = this->GetSourceGroup(currentName);
i = 0; // last component found
}
if(!sg)
{
cmSystemTools::Error("Could not create source group ");
return;
}
// build the whole source group path
for(++i; i<=lastElement; ++i)
{
sg->AddChild(cmSourceGroup(name[i].c_str(), 0, sg->GetFullName()));
sg = sg->LookupChild(name[i].c_str());
}
sg->SetGroupRegex(regex);
}
#endif
static bool mightExpandVariablesCMP0019(const char* s)
{
return s && *s && strstr(s,"${") && strchr(s,'}');
}
void cmMakefile::ExpandVariablesCMP0019()
{
// Drop this ancient compatibility behavior with a policy.
cmPolicies::PolicyStatus pol = this->GetPolicyStatus(cmPolicies::CMP0019);
if(pol != cmPolicies::OLD && pol != cmPolicies::WARN)
{
return;
}
std::ostringstream w;
const char *includeDirs = this->GetProperty("INCLUDE_DIRECTORIES");
if(mightExpandVariablesCMP0019(includeDirs))
{
std::string dirs = includeDirs;
this->ExpandVariablesInString(dirs, true, true);
if(pol == cmPolicies::WARN && dirs != includeDirs)
{
w << "Evaluated directory INCLUDE_DIRECTORIES\n"
<< " " << includeDirs << "\n"
<< "as\n"
<< " " << dirs << "\n";
}
this->SetProperty("INCLUDE_DIRECTORIES", dirs.c_str());
}
// Also for each target's INCLUDE_DIRECTORIES property:
for (cmTargets::iterator l = this->Targets.begin();
l != this->Targets.end(); ++l)
{
cmTarget &t = l->second;
if (t.GetType() == cmTarget::INTERFACE_LIBRARY
|| t.GetType() == cmTarget::GLOBAL_TARGET)
{
continue;
}
includeDirs = t.GetProperty("INCLUDE_DIRECTORIES");
if(mightExpandVariablesCMP0019(includeDirs))
{
std::string dirs = includeDirs;
this->ExpandVariablesInString(dirs, true, true);
if(pol == cmPolicies::WARN && dirs != includeDirs)
{
w << "Evaluated target " << t.GetName() << " INCLUDE_DIRECTORIES\n"
<< " " << includeDirs << "\n"
<< "as\n"
<< " " << dirs << "\n";
}
t.SetProperty("INCLUDE_DIRECTORIES", dirs.c_str());
}
}
if (const char* linkDirsProp = this->GetProperty("LINK_DIRECTORIES"))
{
if(mightExpandVariablesCMP0019(linkDirsProp))
{
std::string d = linkDirsProp;
std::string orig = linkDirsProp;
this->ExpandVariablesInString(d, true, true);
if(pol == cmPolicies::WARN && d != orig)
{
w << "Evaluated link directories\n"
<< " " << orig << "\n"
<< "as\n"
<< " " << d << "\n";
}
}
}
for(cmTarget::LinkLibraryVectorType::iterator l =
this->LinkLibraries.begin();
l != this->LinkLibraries.end(); ++l)
{
if(mightExpandVariablesCMP0019(l->first.c_str()))
{
std::string orig = l->first;
this->ExpandVariablesInString(l->first, true, true);
if(pol == cmPolicies::WARN && l->first != orig)
{
w << "Evaluated link library\n"
<< " " << orig << "\n"
<< "as\n"
<< " " << l->first << "\n";
}
}
}
if(!w.str().empty())
{
std::ostringstream m;
m << cmPolicies::GetPolicyWarning(cmPolicies::CMP0019)
<< "\n"
<< "The following variable evaluations were encountered:\n"
<< w.str();
this->IssueMessage(cmake::AUTHOR_WARNING, m.str());
}
}
bool cmMakefile::IsOn(const std::string& name) const
{
const char* value = this->GetDefinition(name);
return cmSystemTools::IsOn(value);
}
bool cmMakefile::IsSet(const std::string& name) const
{
const char* value = this->GetDefinition(name);
if ( !value )
{
return false;
}
if ( ! *value )
{
return false;
}
if ( cmSystemTools::IsNOTFOUND(value) )
{
return false;
}
return true;
}
bool cmMakefile::PlatformIs64Bit() const
{
if(const char* sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P"))
{
return atoi(sizeof_dptr) == 8;
}
return false;
}
bool cmMakefile::PlatformIsAppleIos() const
{
std::string sdkRoot;
sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
sdkRoot = cmSystemTools::LowerCase(sdkRoot);
return sdkRoot.find("iphoneos") == 0 ||
sdkRoot.find("/iphoneos") != std::string::npos ||
sdkRoot.find("iphonesimulator") == 0 ||
sdkRoot.find("/iphonesimulator") != std::string::npos;
}
const char* cmMakefile::GetSONameFlag(const std::string& language) const
{
std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
if(!language.empty())
{
name += "_";
name += language;
}
name += "_FLAG";
return GetDefinition(name);
}
bool cmMakefile::CanIWriteThisFile(const char* fileName) const
{
if ( !this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES") )
{
return true;
}
// If we are doing an in-source build, then the test will always fail
if ( cmSystemTools::SameFile(this->GetHomeDirectory(),
this->GetHomeOutputDirectory()) )
{
if ( this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD") )
{
return false;
}
return true;
}
// Check if this is a subdirectory of the source tree but not a
// subdirectory of the build tree
if ( cmSystemTools::IsSubDirectory(fileName,
this->GetHomeDirectory()) &&
!cmSystemTools::IsSubDirectory(fileName,
this->GetHomeOutputDirectory()) )
{
return false;
}
return true;
}
const char* cmMakefile::GetRequiredDefinition(const std::string& name) const
{
const char* ret = this->GetDefinition(name);
if(!ret)
{
cmSystemTools::Error("Error required internal CMake variable not "
"set, cmake may be not be built correctly.\n",
"Missing variable is:\n",
name.c_str());
return "";
}
return ret;
}
bool cmMakefile::IsDefinitionSet(const std::string& name) const
{
const char* def = this->StateSnapshot.GetDefinition(name);
if(!def)
{
def = this->GetState()->GetInitializedCacheValue(name);
}
#ifdef CMAKE_BUILD_WITH_CMAKE
if(cmVariableWatch* vv = this->GetVariableWatch())
{
if(!def)
{
vv->VariableAccessed
(name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS,
def, this);
}
}
#endif
return def?true:false;
}
const char* cmMakefile::GetDefinition(const std::string& name) const
{
const char* def = this->StateSnapshot.GetDefinition(name);
if(!def)
{
def = this->GetState()->GetInitializedCacheValue(name);
}
#ifdef CMAKE_BUILD_WITH_CMAKE
cmVariableWatch* vv = this->GetVariableWatch();
if ( vv && !this->SuppressWatches )
{
if ( def )
{
vv->VariableAccessed(name, cmVariableWatch::VARIABLE_READ_ACCESS,
def, this);
}
else
{
vv->VariableAccessed(name,
cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS, def, this);
}
}
#endif
return def;
}
const char* cmMakefile::GetSafeDefinition(const std::string& def) const
{
const char* ret = this->GetDefinition(def);
if(!ret)
{
return "";
}
return ret;
}
std::vector<std::string> cmMakefile::GetDefinitions() const
{
std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
std::vector<std::string> cacheKeys = this->GetState()->GetCacheEntryKeys();
res.insert(res.end(), cacheKeys.begin(), cacheKeys.end());
std::sort(res.begin(), res.end());
return res;
}
const char *cmMakefile::ExpandVariablesInString(std::string& source) const
{
return this->ExpandVariablesInString(source, false, false);
}
const char *cmMakefile::ExpandVariablesInString(std::string& source,
bool escapeQuotes,
bool noEscapes,
bool atOnly,
const char* filename,
long line,
bool removeEmpty,
bool replaceAt) const
{
bool compareResults = false;
cmake::MessageType mtype = cmake::LOG;
std::string errorstr;
std::string original;
// Sanity check the @ONLY mode.
if(atOnly && (!noEscapes || !removeEmpty))
{
// This case should never be called. At-only is for
// configure-file/string which always does no escapes.
this->IssueMessage(cmake::INTERNAL_ERROR,
"ExpandVariablesInString @ONLY called "
"on something with escapes.");
return source.c_str();
}
// Variables used in the WARN case.
std::string newResult;
std::string newErrorstr;
cmake::MessageType newError = cmake::LOG;
switch(this->GetPolicyStatus(cmPolicies::CMP0053))
{
case cmPolicies::WARN:
{
// Save the original string for the warning.
original = source;
newResult = source;
compareResults = true;
// Suppress variable watches to avoid calling hooks twice. Suppress new
// dereferences since the OLD behavior is still what is actually used.
this->SuppressWatches = true;
newError =
ExpandVariablesInStringNew(newErrorstr, newResult, escapeQuotes,
noEscapes, atOnly, filename, line,
removeEmpty, replaceAt);
this->SuppressWatches = false;
}
case cmPolicies::OLD:
mtype = ExpandVariablesInStringOld(errorstr, source, escapeQuotes,
noEscapes, atOnly, filename,
line, removeEmpty, true);
break;
case cmPolicies::REQUIRED_IF_USED:
case cmPolicies::REQUIRED_ALWAYS:
// Messaging here would be *very* verbose.
case cmPolicies::NEW:
mtype = ExpandVariablesInStringNew(errorstr, source, escapeQuotes,
noEscapes, atOnly, filename,
line, removeEmpty, replaceAt);
break;
}
// If it's an error in either case, just report the error...
if(mtype != cmake::LOG)
{
if(mtype == cmake::FATAL_ERROR)
{
cmSystemTools::SetFatalErrorOccured();
}
this->IssueMessage(mtype, errorstr);
}
// ...otherwise, see if there's a difference that needs to be warned about.
else if(compareResults && (newResult != source || newError != mtype))
{
std::string msg =
cmPolicies::GetPolicyWarning(cmPolicies::CMP0053);
msg += "\n";
std::string msg_input = original;
cmSystemTools::ReplaceString(msg_input, "\n", "\n ");
msg += "For input:\n '";
msg += msg_input;
msg += "'\n";
std::string msg_old = source;
cmSystemTools::ReplaceString(msg_old, "\n", "\n ");
msg += "the old evaluation rules produce:\n '";
msg += msg_old;
msg += "'\n";
if(newError == mtype)
{
std::string msg_new = newResult;
cmSystemTools::ReplaceString(msg_new, "\n", "\n ");
msg += "but the new evaluation rules produce:\n '";
msg += msg_new;
msg += "'\n";
}
else
{
std::string msg_err = newErrorstr;
cmSystemTools::ReplaceString(msg_err, "\n", "\n ");
msg += "but the new evaluation rules produce an error:\n ";
msg += msg_err;
msg += "\n";
}
msg +=
"Using the old result for compatibility since the policy is not set.";
this->IssueMessage(cmake::AUTHOR_WARNING, msg);
}
return source.c_str();
}
cmake::MessageType cmMakefile::ExpandVariablesInStringOld(
std::string& errorstr,
std::string& source,
bool escapeQuotes,
bool noEscapes,
bool atOnly,
const char* filename,
long line,
bool removeEmpty,
bool replaceAt) const