1 /*============================================================================
2 CMake - Cross Platform Makefile Generator
3 Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
5 Distributed under the OSI-approved BSD License (the "License");
6 see accompanying file Copyright.txt for details.
8 This software is distributed WITHOUT ANY WARRANTY; without even the
9 implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License for more information.
11 ============================================================================*/
12 #include "cmIfCommand.h"
13 #include "cmStringCommand.h"
15 #include <stdlib.h> // required for atof
17 #include <cmsys/RegularExpression.hxx>
20 static std::string cmIfCommandError(
21 cmMakefile* mf, std::vector<std::string> const& args)
23 cmLocalGenerator* lg = mf->GetLocalGenerator();
24 std::string err = "given arguments:\n ";
25 for(std::vector<std::string>::const_iterator i = args.begin();
29 err += lg->EscapeForCMake(i->c_str());
35 //=========================================================================
36 bool cmIfFunctionBlocker::
37 IsFunctionBlocked(const cmListFileFunction& lff,
39 cmExecutionStatus &inStatus)
41 // we start by recording all the functions
42 if (!cmSystemTools::Strucmp(lff.Name.c_str(),"if"))
46 if (!cmSystemTools::Strucmp(lff.Name.c_str(),"endif"))
49 // if this is the endif for this if statement, then start executing
50 if (!this->ScopeDepth)
52 // Remove the function blocker for this scope or bail.
53 cmsys::auto_ptr<cmFunctionBlocker>
54 fb(mf.RemoveFunctionBlocker(this, lff));
55 if(!fb.get()) { return false; }
57 // execute the functions for the true parts of the if statement
58 cmExecutionStatus status;
60 for(unsigned int c = 0; c < this->Functions.size(); ++c)
62 // keep track of scope depth
63 if (!cmSystemTools::Strucmp(this->Functions[c].Name.c_str(),"if"))
67 if (!cmSystemTools::Strucmp(this->Functions[c].Name.c_str(),"endif"))
71 // watch for our state change
72 if (scopeDepth == 0 &&
73 !cmSystemTools::Strucmp(this->Functions[c].Name.c_str(),"else"))
75 this->IsBlocking = this->HasRun;
78 // if trace is enabled, print a (trivially) evaluated "else"
80 if(!this->IsBlocking && mf.GetCMakeInstance()->GetTrace())
82 mf.PrintCommandTrace(this->Functions[c]);
85 else if (scopeDepth == 0 && !cmSystemTools::Strucmp
86 (this->Functions[c].Name.c_str(),"elseif"))
90 this->IsBlocking = true;
94 // Place this call on the call stack.
95 cmMakefileCall stack_manager(&mf, this->Functions[c], status);
96 static_cast<void>(stack_manager);
98 // if trace is enabled, print the evaluated "elseif" statement
99 if(mf.GetCMakeInstance()->GetTrace())
101 mf.PrintCommandTrace(this->Functions[c]);
104 std::string errorString;
106 std::vector<std::string> expandedArguments;
107 mf.ExpandArguments(this->Functions[c].Arguments,
110 cmake::MessageType messType;
112 cmIfCommand::IsTrue(expandedArguments, errorString,
115 if (errorString.size())
117 std::string err = cmIfCommandError(&mf, expandedArguments);
119 mf.IssueMessage(messType, err);
120 if (messType == cmake::FATAL_ERROR)
122 cmSystemTools::SetFatalErrorOccured();
129 this->IsBlocking = false;
135 // should we execute?
136 else if (!this->IsBlocking)
139 mf.ExecuteCommand(this->Functions[c],status);
140 if (status.GetReturnInvoked())
142 inStatus.SetReturnInvoked(true);
145 if (status.GetBreakInvoked())
147 inStatus.SetBreakInvoked(true);
156 // record the command
157 this->Functions.push_back(lff);
159 // always return true
163 //=========================================================================
164 bool cmIfFunctionBlocker::ShouldRemove(const cmListFileFunction& lff,
167 if (!cmSystemTools::Strucmp(lff.Name.c_str(),"endif"))
169 // if the endif has arguments, then make sure
170 // they match the arguments of the matching if
171 if (lff.Arguments.size() == 0 ||
172 lff.Arguments == this->Args)
181 //=========================================================================
183 ::InvokeInitialPass(const std::vector<cmListFileArgument>& args,
186 std::string errorString;
188 std::vector<std::string> expandedArguments;
189 this->Makefile->ExpandArguments(args, expandedArguments);
191 cmake::MessageType status;
193 cmIfCommand::IsTrue(expandedArguments,errorString,
194 this->Makefile, status);
196 if (errorString.size())
198 std::string err = cmIfCommandError(this->Makefile, expandedArguments);
200 if (status == cmake::FATAL_ERROR)
202 this->SetError(err.c_str());
203 cmSystemTools::SetFatalErrorOccured();
208 this->Makefile->IssueMessage(status, err);
212 cmIfFunctionBlocker *f = new cmIfFunctionBlocker();
213 // if is isn't true block the commands
215 f->IsBlocking = !isTrue;
221 this->Makefile->AddFunctionBlocker(f);
228 //=========================================================================
229 bool GetBooleanValue(std::string& arg, cmMakefile* mf)
231 // Check basic constants.
241 // Check named constants.
242 if (cmSystemTools::IsOn(arg.c_str()))
246 if (cmSystemTools::IsOff(arg.c_str()))
251 // Check for numbers.
255 double d = strtod(arg.c_str(), &end);
258 // The whole string is a number. Use C conversion to bool.
259 return d? true:false;
264 const char* def = mf->GetDefinition(arg.c_str());
265 return !cmSystemTools::IsOff(def);
268 //=========================================================================
269 // Boolean value behavior from CMake 2.6.4 and below.
270 bool GetBooleanValueOld(std::string const& arg, cmMakefile* mf, bool one)
274 // Old IsTrue behavior for single argument.
280 { return !cmSystemTools::IsOff(mf->GetDefinition(arg.c_str())); }
284 // Old GetVariableOrNumber behavior.
285 const char* def = mf->GetDefinition(arg.c_str());
286 if(!def && atoi(arg.c_str()))
290 return !cmSystemTools::IsOff(def);
294 //=========================================================================
295 // returns the resulting boolean value
296 bool GetBooleanValueWithAutoDereference(
298 cmMakefile *makefile,
299 std::string &errorString,
300 cmPolicies::PolicyStatus Policy12Status,
301 cmake::MessageType &status,
304 // Use the policy if it is set.
305 if (Policy12Status == cmPolicies::NEW)
307 return GetBooleanValue(newArg, makefile);
309 else if (Policy12Status == cmPolicies::OLD)
311 return GetBooleanValueOld(newArg, makefile, oneArg);
314 // Check policy only if old and new results differ.
315 bool newResult = GetBooleanValue(newArg, makefile);
316 bool oldResult = GetBooleanValueOld(newArg, makefile, oneArg);
317 if(newResult != oldResult)
319 switch(Policy12Status)
321 case cmPolicies::WARN:
323 cmPolicies* policies = makefile->GetPolicies();
324 errorString = "An argument named \"" + newArg
325 + "\" appears in a conditional statement. "
326 + policies->GetPolicyWarning(cmPolicies::CMP0012);
327 status = cmake::AUTHOR_WARNING;
329 case cmPolicies::OLD:
331 case cmPolicies::REQUIRED_IF_USED:
332 case cmPolicies::REQUIRED_ALWAYS:
334 cmPolicies* policies = makefile->GetPolicies();
335 errorString = "An argument named \"" + newArg
336 + "\" appears in a conditional statement. "
337 + policies->GetRequiredPolicyError(cmPolicies::CMP0012);
338 status = cmake::FATAL_ERROR;
340 case cmPolicies::NEW:
347 //=========================================================================
348 void IncrementArguments(std::list<std::string> &newArgs,
349 std::list<std::string>::iterator &argP1,
350 std::list<std::string>::iterator &argP2)
352 if (argP1 != newArgs.end())
356 if (argP1 != newArgs.end())
363 //=========================================================================
364 // helper function to reduce code duplication
365 void HandlePredicate(bool value, int &reducible,
366 std::list<std::string>::iterator &arg,
367 std::list<std::string> &newArgs,
368 std::list<std::string>::iterator &argP1,
369 std::list<std::string>::iterator &argP2)
379 newArgs.erase(argP1);
381 IncrementArguments(newArgs,argP1,argP2);
385 //=========================================================================
386 // helper function to reduce code duplication
387 void HandleBinaryOp(bool value, int &reducible,
388 std::list<std::string>::iterator &arg,
389 std::list<std::string> &newArgs,
390 std::list<std::string>::iterator &argP1,
391 std::list<std::string>::iterator &argP2)
401 newArgs.erase(argP2);
402 newArgs.erase(argP1);
404 IncrementArguments(newArgs,argP1,argP2);
408 //=========================================================================
409 enum Op { OpLess, OpEqual, OpGreater };
410 bool HandleVersionCompare(Op op, const char* lhs_str, const char* rhs_str)
412 // Parse out up to 4 components.
413 unsigned int lhs[4] = {0,0,0,0};
414 unsigned int rhs[4] = {0,0,0,0};
415 sscanf(lhs_str, "%u.%u.%u.%u", &lhs[0], &lhs[1], &lhs[2], &lhs[3]);
416 sscanf(rhs_str, "%u.%u.%u.%u", &rhs[0], &rhs[1], &rhs[2], &rhs[3]);
418 // Do component-wise comparison.
419 for(unsigned int i=0; i < 4; ++i)
423 // lhs < rhs, so true if operation is LESS
426 else if(lhs[i] > rhs[i])
428 // lhs > rhs, so true if operation is GREATER
429 return op == OpGreater;
432 // lhs == rhs, so true if operation is EQUAL
433 return op == OpEqual;
436 //=========================================================================
437 // level 0 processes parenthetical expressions
438 bool HandleLevel0(std::list<std::string> &newArgs,
439 cmMakefile *makefile,
440 std::string &errorString,
441 cmake::MessageType &status)
447 std::list<std::string>::iterator arg = newArgs.begin();
448 while (arg != newArgs.end())
452 // search for the closing paren for this opening one
453 std::list<std::string>::iterator argClose;
456 unsigned int depth = 1;
457 while (argClose != newArgs.end() && depth)
459 if (*argClose == "(")
463 if (*argClose == ")")
471 errorString = "mismatched parenthesis in condition";
472 status = cmake::FATAL_ERROR;
475 // store the reduced args in this vector
476 std::vector<std::string> newArgs2;
478 // copy to the list structure
479 std::list<std::string>::iterator argP1 = arg;
481 for(; argP1 != argClose; argP1++)
483 newArgs2.push_back(*argP1);
486 // now recursively invoke IsTrue to handle the values inside the
487 // parenthetical expression
489 cmIfCommand::IsTrue(newArgs2, errorString, makefile, status);
500 // remove the now evaluated parenthetical expression
501 newArgs.erase(argP1,argClose);
510 //=========================================================================
511 // level one handles most predicates except for NOT
512 bool HandleLevel1(std::list<std::string> &newArgs,
513 cmMakefile *makefile,
514 std::string &, cmake::MessageType &)
520 std::list<std::string>::iterator arg = newArgs.begin();
521 std::list<std::string>::iterator argP1;
522 std::list<std::string>::iterator argP2;
523 while (arg != newArgs.end())
526 IncrementArguments(newArgs,argP1,argP2);
528 if (*arg == "EXISTS" && argP1 != newArgs.end())
531 cmSystemTools::FileExists((argP1)->c_str()),
532 reducible, arg, newArgs, argP1, argP2);
534 // does a directory with this name exist
535 if (*arg == "IS_DIRECTORY" && argP1 != newArgs.end())
538 cmSystemTools::FileIsDirectory((argP1)->c_str()),
539 reducible, arg, newArgs, argP1, argP2);
541 // does a symlink with this name exist
542 if (*arg == "IS_SYMLINK" && argP1 != newArgs.end())
545 cmSystemTools::FileIsSymlink((argP1)->c_str()),
546 reducible, arg, newArgs, argP1, argP2);
548 // is the given path an absolute path ?
549 if (*arg == "IS_ABSOLUTE" && argP1 != newArgs.end())
552 cmSystemTools::FileIsFullPath((argP1)->c_str()),
553 reducible, arg, newArgs, argP1, argP2);
555 // does a command exist
556 if (*arg == "COMMAND" && argP1 != newArgs.end())
559 makefile->CommandExists((argP1)->c_str()),
560 reducible, arg, newArgs, argP1, argP2);
562 // does a policy exist
563 if (*arg == "POLICY" && argP1 != newArgs.end())
565 cmPolicies::PolicyID pid;
567 makefile->GetPolicies()->GetPolicyID((argP1)->c_str(), pid),
568 reducible, arg, newArgs, argP1, argP2);
570 // does a target exist
571 if (*arg == "TARGET" && argP1 != newArgs.end())
574 makefile->FindTargetToUse((argP1)->c_str())? true:false,
575 reducible, arg, newArgs, argP1, argP2);
577 // is a variable defined
578 if (*arg == "DEFINED" && argP1 != newArgs.end())
580 size_t argP1len = argP1->size();
582 if(argP1len > 4 && argP1->substr(0, 4) == "ENV{" &&
583 argP1->operator[](argP1len-1) == '}')
585 std::string env = argP1->substr(4, argP1len-5);
586 bdef = cmSystemTools::GetEnv(env.c_str())?true:false;
590 bdef = makefile->IsDefinitionSet((argP1)->c_str());
592 HandlePredicate(bdef, reducible, arg, newArgs, argP1, argP2);
601 //=========================================================================
602 // level two handles most binary operations except for AND OR
603 bool HandleLevel2(std::list<std::string> &newArgs,
604 cmMakefile *makefile,
605 std::string &errorString,
606 cmake::MessageType &status)
614 std::list<std::string>::iterator arg = newArgs.begin();
615 std::list<std::string>::iterator argP1;
616 std::list<std::string>::iterator argP2;
617 while (arg != newArgs.end())
620 IncrementArguments(newArgs,argP1,argP2);
621 if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
622 *(argP1) == "MATCHES")
624 def = cmIfCommand::GetVariableOrString(arg->c_str(), makefile);
625 const char* rex = (argP2)->c_str();
626 cmStringCommand::ClearMatches(makefile);
627 cmsys::RegularExpression regEntry;
628 if ( !regEntry.compile(rex) )
630 cmOStringStream error;
631 error << "Regular expression \"" << rex << "\" cannot compile";
632 errorString = error.str();
633 status = cmake::FATAL_ERROR;
636 if (regEntry.find(def))
638 cmStringCommand::StoreMatches(makefile, regEntry);
645 newArgs.erase(argP2);
646 newArgs.erase(argP1);
648 IncrementArguments(newArgs,argP1,argP2);
652 if (argP1 != newArgs.end() && *arg == "MATCHES")
655 newArgs.erase(argP1);
657 IncrementArguments(newArgs,argP1,argP2);
661 if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
662 (*(argP1) == "LESS" || *(argP1) == "GREATER" ||
663 *(argP1) == "EQUAL"))
665 def = cmIfCommand::GetVariableOrString(arg->c_str(), makefile);
666 def2 = cmIfCommand::GetVariableOrString((argP2)->c_str(), makefile);
670 if(sscanf(def, "%lg", &lhs) != 1 ||
671 sscanf(def2, "%lg", &rhs) != 1)
675 else if (*(argP1) == "LESS")
677 result = (lhs < rhs);
679 else if (*(argP1) == "GREATER")
681 result = (lhs > rhs);
685 result = (lhs == rhs);
687 HandleBinaryOp(result,
688 reducible, arg, newArgs, argP1, argP2);
691 if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
692 (*(argP1) == "STRLESS" ||
693 *(argP1) == "STREQUAL" ||
694 *(argP1) == "STRGREATER"))
696 def = cmIfCommand::GetVariableOrString(arg->c_str(), makefile);
697 def2 = cmIfCommand::GetVariableOrString((argP2)->c_str(), makefile);
698 int val = strcmp(def,def2);
700 if (*(argP1) == "STRLESS")
704 else if (*(argP1) == "STRGREATER")
712 HandleBinaryOp(result,
713 reducible, arg, newArgs, argP1, argP2);
716 if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
717 (*(argP1) == "VERSION_LESS" || *(argP1) == "VERSION_GREATER" ||
718 *(argP1) == "VERSION_EQUAL"))
720 def = cmIfCommand::GetVariableOrString(arg->c_str(), makefile);
721 def2 = cmIfCommand::GetVariableOrString((argP2)->c_str(), makefile);
723 if(*argP1 == "VERSION_LESS")
727 else if(*argP1 == "VERSION_GREATER")
731 bool result = HandleVersionCompare(op, def, def2);
732 HandleBinaryOp(result,
733 reducible, arg, newArgs, argP1, argP2);
736 // is file A newer than file B
737 if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
738 *(argP1) == "IS_NEWER_THAN")
741 bool success=cmSystemTools::FileTimeCompare(arg->c_str(),
745 (success==false || fileIsNewer==1 || fileIsNewer==0),
746 reducible, arg, newArgs, argP1, argP2);
756 //=========================================================================
757 // level 3 handles NOT
758 bool HandleLevel3(std::list<std::string> &newArgs,
759 cmMakefile *makefile,
760 std::string &errorString,
761 cmPolicies::PolicyStatus Policy12Status,
762 cmake::MessageType &status)
768 std::list<std::string>::iterator arg = newArgs.begin();
769 std::list<std::string>::iterator argP1;
770 std::list<std::string>::iterator argP2;
771 while (arg != newArgs.end())
774 IncrementArguments(newArgs,argP1,argP2);
775 if (argP1 != newArgs.end() && *arg == "NOT")
777 bool rhs = GetBooleanValueWithAutoDereference(*argP1, makefile,
781 HandlePredicate(!rhs, reducible, arg, newArgs, argP1, argP2);
790 //=========================================================================
791 // level 4 handles AND OR
792 bool HandleLevel4(std::list<std::string> &newArgs,
793 cmMakefile *makefile,
794 std::string &errorString,
795 cmPolicies::PolicyStatus Policy12Status,
796 cmake::MessageType &status)
804 std::list<std::string>::iterator arg = newArgs.begin();
805 std::list<std::string>::iterator argP1;
806 std::list<std::string>::iterator argP2;
807 while (arg != newArgs.end())
810 IncrementArguments(newArgs,argP1,argP2);
811 if (argP1 != newArgs.end() && *(argP1) == "AND" &&
812 argP2 != newArgs.end())
814 lhs = GetBooleanValueWithAutoDereference(*arg, makefile,
818 rhs = GetBooleanValueWithAutoDereference(*argP2, makefile,
822 HandleBinaryOp((lhs && rhs),
823 reducible, arg, newArgs, argP1, argP2);
826 if (argP1 != newArgs.end() && *(argP1) == "OR" &&
827 argP2 != newArgs.end())
829 lhs = GetBooleanValueWithAutoDereference(*arg, makefile,
833 rhs = GetBooleanValueWithAutoDereference(*argP2, makefile,
837 HandleBinaryOp((lhs || rhs),
838 reducible, arg, newArgs, argP1, argP2);
849 //=========================================================================
850 // order of operations,
851 // 1. ( ) -- parenthetical groups
852 // 2. IS_DIRECTORY EXISTS COMMAND DEFINED etc predicates
853 // 3. MATCHES LESS GREATER EQUAL STRLESS STRGREATER STREQUAL etc binary ops
857 // There is an issue on whether the arguments should be values of references,
858 // for example IF (FOO AND BAR) should that compare the strings FOO and BAR
859 // or should it really do IF (${FOO} AND ${BAR}) Currently IS_DIRECTORY
860 // EXISTS COMMAND and DEFINED all take values. EQUAL, LESS and GREATER can
861 // take numeric values or variable names. STRLESS and STRGREATER take
862 // variable names but if the variable name is not found it will use the name
863 // directly. AND OR take variables or the values 0 or 1.
866 bool cmIfCommand::IsTrue(const std::vector<std::string> &args,
867 std::string &errorString, cmMakefile *makefile,
868 cmake::MessageType &status)
872 // handle empty invocation
878 // store the reduced args in this vector
879 std::list<std::string> newArgs;
881 // copy to the list structure
882 for(unsigned int i = 0; i < args.size(); ++i)
884 newArgs.push_back(args[i]);
887 // now loop through the arguments and see if we can reduce any of them
888 // we do this multiple times. Once for each level of precedence
890 if (!HandleLevel0(newArgs, makefile, errorString, status))
895 if (!HandleLevel1(newArgs, makefile, errorString, status))
900 if (!HandleLevel2(newArgs, makefile, errorString, status))
905 // used to store the value of policy CMP0012 for performance
906 cmPolicies::PolicyStatus Policy12Status =
907 makefile->GetPolicyStatus(cmPolicies::CMP0012);
910 if (!HandleLevel3(newArgs, makefile, errorString,
911 Policy12Status, status))
916 if (!HandleLevel4(newArgs, makefile, errorString,
917 Policy12Status, status))
922 // now at the end there should only be one argument left
923 if (newArgs.size() != 1)
925 errorString = "Unknown arguments specified";
926 status = cmake::FATAL_ERROR;
930 return GetBooleanValueWithAutoDereference(*(newArgs.begin()),
937 //=========================================================================
938 const char* cmIfCommand::GetVariableOrString(const char* str,
939 const cmMakefile* mf)
941 const char* def = mf->GetDefinition(str);