diff options
author | Patrick Wildt <patrick@cvs.openbsd.org> | 2017-01-24 08:33:39 +0000 |
---|---|---|
committer | Patrick Wildt <patrick@cvs.openbsd.org> | 2017-01-24 08:33:39 +0000 |
commit | 191f5aec14fa2cfaf2f023580df9ac81db321223 (patch) | |
tree | 54650dd8fc4a937b4efa5c479f29f9bd9f218975 /gnu/llvm/utils | |
parent | c5c5d71a3c51a145ba9d0a7d2f3ca2be4d6a2131 (diff) |
Import LLVM 4.0.0 rc1 including clang and lld to help the current
development effort on OpenBSD/arm64.
Diffstat (limited to 'gnu/llvm/utils')
141 files changed, 26282 insertions, 4063 deletions
diff --git a/gnu/llvm/utils/FileCheck/FileCheck.cpp b/gnu/llvm/utils/FileCheck/FileCheck.cpp index 6c9b62d5b24..9e177574625 100644 --- a/gnu/llvm/utils/FileCheck/FileCheck.cpp +++ b/gnu/llvm/utils/FileCheck/FileCheck.cpp @@ -36,24 +36,24 @@ using namespace llvm; static cl::opt<std::string> -CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required); + CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required); static cl::opt<std::string> -InputFilename("input-file", cl::desc("File to check (defaults to stdin)"), - cl::init("-"), cl::value_desc("filename")); + InputFilename("input-file", cl::desc("File to check (defaults to stdin)"), + cl::init("-"), cl::value_desc("filename")); -static cl::list<std::string> -CheckPrefixes("check-prefix", - cl::desc("Prefix to use from check file (defaults to 'CHECK')")); +static cl::list<std::string> CheckPrefixes( + "check-prefix", + cl::desc("Prefix to use from check file (defaults to 'CHECK')")); static cl::alias CheckPrefixesAlias( "check-prefixes", cl::aliasopt(CheckPrefixes), cl::CommaSeparated, cl::NotHidden, cl::desc( "Alias for -check-prefix permitting multiple comma separated values")); -static cl::opt<bool> -NoCanonicalizeWhiteSpace("strict-whitespace", - cl::desc("Do not treat all horizontal whitespace as equivalent")); +static cl::opt<bool> NoCanonicalizeWhiteSpace( + "strict-whitespace", + cl::desc("Do not treat all horizontal whitespace as equivalent")); static cl::list<std::string> ImplicitCheckNot( "implicit-check-not", @@ -80,128 +80,104 @@ typedef cl::list<std::string>::const_iterator prefix_iterator; //===----------------------------------------------------------------------===// namespace Check { - enum CheckType { - CheckNone = 0, - CheckPlain, - CheckNext, - CheckSame, - CheckNot, - CheckDAG, - CheckLabel, - - /// MatchEOF - When set, this pattern only matches the end of file. This is - /// used for trailing CHECK-NOTs. - CheckEOF, - /// CheckBadNot - Found -NOT combined with another CHECK suffix. - CheckBadNot - }; +enum CheckType { + CheckNone = 0, + CheckPlain, + CheckNext, + CheckSame, + CheckNot, + CheckDAG, + CheckLabel, + + /// Indicates the pattern only matches the end of file. This is used for + /// trailing CHECK-NOTs. + CheckEOF, + + /// Marks when parsing found a -NOT check combined with another CHECK suffix. + CheckBadNot +}; } class Pattern { SMLoc PatternLoc; - Check::CheckType CheckTy; - - /// FixedStr - If non-empty, this pattern is a fixed string match with the - /// specified fixed string. + /// A fixed string to match as the pattern or empty if this pattern requires + /// a regex match. StringRef FixedStr; - /// RegEx - If non-empty, this is a regex pattern. + /// A regex string to match as the pattern or empty if this pattern requires + /// a fixed string to match. std::string RegExStr; - /// \brief Contains the number of line this pattern is in. - unsigned LineNumber; - - /// VariableUses - Entries in this vector map to uses of a variable in the - /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain - /// "foobaz" and we'll get an entry in this vector that tells us to insert the - /// value of bar at offset 3. - std::vector<std::pair<StringRef, unsigned> > VariableUses; + /// Entries in this vector map to uses of a variable in the pattern, e.g. + /// "foo[[bar]]baz". In this case, the RegExStr will contain "foobaz" and + /// we'll get an entry in this vector that tells us to insert the value of + /// bar at offset 3. + std::vector<std::pair<StringRef, unsigned>> VariableUses; - /// VariableDefs - Maps definitions of variables to their parenthesized - /// capture numbers. - /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1. + /// Maps definitions of variables to their parenthesized capture numbers. + /// + /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to + /// 1. std::map<StringRef, unsigned> VariableDefs; -public: + Check::CheckType CheckTy; - Pattern(Check::CheckType Ty) - : CheckTy(Ty) { } + /// Contains the number of line this pattern is in. + unsigned LineNumber; - /// getLoc - Return the location in source code. +public: + explicit Pattern(Check::CheckType Ty) : CheckTy(Ty) {} + + /// Returns the location in source code. SMLoc getLoc() const { return PatternLoc; } - /// ParsePattern - Parse the given string into the Pattern. Prefix provides - /// which prefix is being matched, SM provides the SourceMgr used for error - /// reports, and LineNumber is the line number in the input file from which - /// the pattern string was read. Returns true in case of an error, false - /// otherwise. - bool ParsePattern(StringRef PatternStr, - StringRef Prefix, - SourceMgr &SM, + bool ParsePattern(StringRef PatternStr, StringRef Prefix, SourceMgr &SM, unsigned LineNumber); - - /// Match - Match the pattern string against the input buffer Buffer. This - /// returns the position that is matched or npos if there is no match. If - /// there is a match, the size of the matched string is returned in MatchLen. - /// - /// The VariableTable StringMap provides the current values of filecheck - /// variables and is updated if this match defines new values. size_t Match(StringRef Buffer, size_t &MatchLen, StringMap<StringRef> &VariableTable) const; - - /// PrintFailureInfo - Print additional information about a failure to match - /// involving this pattern. void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, const StringMap<StringRef> &VariableTable) const; - bool hasVariable() const { return !(VariableUses.empty() && - VariableDefs.empty()); } + bool hasVariable() const { + return !(VariableUses.empty() && VariableDefs.empty()); + } Check::CheckType getCheckTy() const { return CheckTy; } private: bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM); void AddBackrefToRegEx(unsigned BackrefNum); - - /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of - /// matching this pattern at the start of \arg Buffer; a distance of zero - /// should correspond to a perfect match. - unsigned ComputeMatchDistance(StringRef Buffer, - const StringMap<StringRef> &VariableTable) const; - - /// \brief Evaluates expression and stores the result to \p Value. - /// \return true on success. false when the expression has invalid syntax. + unsigned + ComputeMatchDistance(StringRef Buffer, + const StringMap<StringRef> &VariableTable) const; bool EvaluateExpression(StringRef Expr, std::string &Value) const; - - /// \brief Finds the closing sequence of a regex variable usage or - /// definition. Str has to point in the beginning of the definition - /// (right after the opening sequence). - /// \return offset of the closing sequence within Str, or npos if it was not - /// found. size_t FindRegexVarEnd(StringRef Str, SourceMgr &SM); }; - -bool Pattern::ParsePattern(StringRef PatternStr, - StringRef Prefix, - SourceMgr &SM, - unsigned LineNumber) { +/// Parses the given string into the Pattern. +/// +/// \p Prefix provides which prefix is being matched, \p SM provides the +/// SourceMgr used for error reports, and \p LineNumber is the line number in +/// the input file from which the pattern string was read. Returns true in +/// case of an error, false otherwise. +bool Pattern::ParsePattern(StringRef PatternStr, StringRef Prefix, + SourceMgr &SM, unsigned LineNumber) { bool MatchFullLinesHere = MatchFullLines && CheckTy != Check::CheckNot; this->LineNumber = LineNumber; PatternLoc = SMLoc::getFromPointer(PatternStr.data()); - // Ignore trailing whitespace. - while (!PatternStr.empty() && - (PatternStr.back() == ' ' || PatternStr.back() == '\t')) - PatternStr = PatternStr.substr(0, PatternStr.size()-1); + if (!(NoCanonicalizeWhiteSpace && MatchFullLines)) + // Ignore trailing whitespace. + while (!PatternStr.empty() && + (PatternStr.back() == ' ' || PatternStr.back() == '\t')) + PatternStr = PatternStr.substr(0, PatternStr.size() - 1); // Check that there is something on the line. if (PatternStr.empty()) { SM.PrintMessage(PatternLoc, SourceMgr::DK_Error, - "found empty check string with prefix '" + - Prefix + ":'"); + "found empty check string with prefix '" + Prefix + ":'"); return true; } @@ -244,11 +220,11 @@ bool Pattern::ParsePattern(StringRef PatternStr, RegExStr += '('; ++CurParen; - if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM)) + if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM)) return true; RegExStr += ')'; - PatternStr = PatternStr.substr(End+2); + PatternStr = PatternStr.substr(End + 2); continue; } @@ -270,7 +246,7 @@ bool Pattern::ParsePattern(StringRef PatternStr, } StringRef MatchStr = PatternStr.substr(2, End); - PatternStr = PatternStr.substr(End+4); + PatternStr = PatternStr.substr(End + 4); // Get the regex name (e.g. "foo"). size_t NameEnd = MatchStr.find(':'); @@ -299,7 +275,7 @@ bool Pattern::ParsePattern(StringRef PatternStr, } if (Name[i] != '_' && !isalnum(Name[i]) && (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) { - SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i), + SM.PrintMessage(SMLoc::getFromPointer(Name.data() + i), SourceMgr::DK_Error, "invalid name in named regex"); return true; } @@ -336,7 +312,7 @@ bool Pattern::ParsePattern(StringRef PatternStr, RegExStr += '('; ++CurParen; - if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM)) + if (AddRegExToRegEx(MatchStr.substr(NameEnd + 1), CurParen, SM)) return true; RegExStr += ')'; @@ -359,8 +335,7 @@ bool Pattern::ParsePattern(StringRef PatternStr, return false; } -bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, - SourceMgr &SM) { +bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) { Regex R(RS); std::string Error; if (!R.isValid(Error)) { @@ -376,11 +351,13 @@ bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, void Pattern::AddBackrefToRegEx(unsigned BackrefNum) { assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number"); - std::string Backref = std::string("\\") + - std::string(1, '0' + BackrefNum); + std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum); RegExStr += Backref; } +/// Evaluates expression and stores the result to \p Value. +/// +/// Returns true on success and false when the expression has invalid syntax. bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const { // The only supported expression is @LINE([\+-]\d+)? if (!Expr.startswith("@LINE")) @@ -399,9 +376,14 @@ bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const { return true; } -/// Match - Match the pattern string against the input buffer Buffer. This -/// returns the position that is matched or npos if there is no match. If -/// there is a match, the size of the matched string is returned in MatchLen. +/// Matches the pattern string against the input buffer \p Buffer +/// +/// This returns the position that is matched or npos if there is no match. If +/// there is a match, the size of the matched string is returned in \p +/// MatchLen. +/// +/// The \p VariableTable StringMap provides the current values of filecheck +/// variables and is updated if this match defines new values. size_t Pattern::Match(StringRef Buffer, size_t &MatchLen, StringMap<StringRef> &VariableTable) const { // If this is the EOF pattern, match it immediately. @@ -453,7 +435,6 @@ size_t Pattern::Match(StringRef Buffer, size_t &MatchLen, RegExToMatch = TmpStr; } - SmallVector<StringRef, 4> MatchInfo; if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo)) return StringRef::npos; @@ -469,10 +450,15 @@ size_t Pattern::Match(StringRef Buffer, size_t &MatchLen, } MatchLen = FullMatch.size(); - return FullMatch.data()-Buffer.data(); + return FullMatch.data() - Buffer.data(); } -unsigned Pattern::ComputeMatchDistance(StringRef Buffer, + +/// Computes an arbitrary estimate for the quality of matching this pattern at +/// the start of \p Buffer; a distance of zero should correspond to a perfect +/// match. +unsigned +Pattern::ComputeMatchDistance(StringRef Buffer, const StringMap<StringRef> &VariableTable) const { // Just compute the number of matching characters. For regular expressions, we // just compare against the regex itself and hope for the best. @@ -490,8 +476,11 @@ unsigned Pattern::ComputeMatchDistance(StringRef Buffer, return BufferPrefix.edit_distance(ExampleString); } -void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, - const StringMap<StringRef> &VariableTable) const{ +/// Prints additional information about a failure to match involving this +/// pattern. +void Pattern::PrintFailureInfo( + const SourceMgr &SM, StringRef Buffer, + const StringMap<StringRef> &VariableTable) const { // If this was a regular expression using variables, print the current // variable values. if (!VariableUses.empty()) { @@ -561,14 +550,19 @@ void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, // reasonable and not equal to what we showed in the "scanning from here" // line. if (Best && Best != StringRef::npos && BestQuality < 50) { - SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best), - SourceMgr::DK_Note, "possible intended match here"); + SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best), + SourceMgr::DK_Note, "possible intended match here"); // FIXME: If we wanted to be really friendly we would show why the match // failed, as it can be hard to spot simple one character differences. } } +/// Finds the closing sequence of a regex variable usage or definition. +/// +/// \p Str has to point in the beginning of the definition (right after the +/// opening sequence). Returns the offset of the closing sequence within Str, +/// or npos if it was not found. size_t Pattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) { // Offset keeps track of the current offset within the input Str size_t Offset = 0; @@ -584,20 +578,20 @@ size_t Pattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) { Offset += 2; } else { switch (Str[0]) { - default: - break; - case '[': - BracketDepth++; - break; - case ']': - if (BracketDepth == 0) { - SM.PrintMessage(SMLoc::getFromPointer(Str.data()), - SourceMgr::DK_Error, - "missing closing \"]\" for regex variable"); - exit(1); - } - BracketDepth--; - break; + default: + break; + case '[': + BracketDepth++; + break; + case ']': + if (BracketDepth == 0) { + SM.PrintMessage(SMLoc::getFromPointer(Str.data()), + SourceMgr::DK_Error, + "missing closing \"]\" for regex variable"); + exit(1); + } + BracketDepth--; + break; } Str = Str.substr(1); Offset++; @@ -607,67 +601,48 @@ size_t Pattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) { return StringRef::npos; } - //===----------------------------------------------------------------------===// // Check Strings. //===----------------------------------------------------------------------===// -/// CheckString - This is a check that we found in the input file. +/// A check that we found in the input file. struct CheckString { - /// Pat - The pattern to match. + /// The pattern to match. Pattern Pat; - /// Prefix - Which prefix name this check matched. + /// Which prefix name this check matched. StringRef Prefix; - /// Loc - The location in the match file that the check string was specified. + /// The location in the match file that the check string was specified. SMLoc Loc; - /// CheckTy - Specify what kind of check this is. e.g. CHECK-NEXT: directive, - /// as opposed to a CHECK: directive. - // Check::CheckType CheckTy; - - /// DagNotStrings - These are all of the strings that are disallowed from - /// occurring between this match string and the previous one (or start of - /// file). + /// All of the strings that are disallowed from occurring between this match + /// string and the previous one (or start of file). std::vector<Pattern> DagNotStrings; CheckString(const Pattern &P, StringRef S, SMLoc L) : Pat(P), Prefix(S), Loc(L) {} - /// Check - Match check string and its "not strings" and/or "dag strings". size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode, size_t &MatchLen, StringMap<StringRef> &VariableTable) const; - /// CheckNext - Verify there is a single line in the given buffer. bool CheckNext(const SourceMgr &SM, StringRef Buffer) const; - - /// CheckSame - Verify there is no newline in the given buffer. bool CheckSame(const SourceMgr &SM, StringRef Buffer) const; - - /// CheckNot - Verify there's no "not strings" in the given buffer. bool CheckNot(const SourceMgr &SM, StringRef Buffer, const std::vector<const Pattern *> &NotStrings, StringMap<StringRef> &VariableTable) const; - - /// CheckDag - Match "dag strings" and their mixed "not strings". size_t CheckDag(const SourceMgr &SM, StringRef Buffer, std::vector<const Pattern *> &NotStrings, StringMap<StringRef> &VariableTable) const; }; -/// Canonicalize whitespaces in the input file. Line endings are replaced -/// with UNIX-style '\n'. -/// -/// \param PreserveHorizontal Don't squash consecutive horizontal whitespace -/// characters to a single space. -static std::unique_ptr<MemoryBuffer> -CanonicalizeInputFile(std::unique_ptr<MemoryBuffer> MB, - bool PreserveHorizontal) { - SmallString<128> NewFile; - NewFile.reserve(MB->getBufferSize()); - - for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd(); +/// Canonicalize whitespaces in the file. Line endings are replaced with +/// UNIX-style '\n'. +static StringRef CanonicalizeFile(MemoryBuffer &MB, + SmallVectorImpl<char> &OutputBuffer) { + OutputBuffer.reserve(MB.getBufferSize()); + + for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd(); Ptr != End; ++Ptr) { // Eliminate trailing dosish \r. if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') { @@ -676,20 +651,20 @@ CanonicalizeInputFile(std::unique_ptr<MemoryBuffer> MB, // If current char is not a horizontal whitespace or if horizontal // whitespace canonicalization is disabled, dump it to output as is. - if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) { - NewFile.push_back(*Ptr); + if (NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) { + OutputBuffer.push_back(*Ptr); continue; } // Otherwise, add one space and advance over neighboring space. - NewFile.push_back(' '); - while (Ptr+1 != End && - (Ptr[1] == ' ' || Ptr[1] == '\t')) + OutputBuffer.push_back(' '); + while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t')) ++Ptr; } - return std::unique_ptr<MemoryBuffer>( - MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier())); + // Add a null byte and then return all but that byte. + OutputBuffer.push_back('\0'); + return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1); } static bool IsPartOfWord(char c) { @@ -770,119 +745,77 @@ static size_t SkipWord(StringRef Str, size_t Loc) { return Loc; } -// Try to find the first match in buffer for any prefix. If a valid match is -// found, return that prefix and set its type and location. If there are almost -// matches (e.g. the actual prefix string is found, but is not an actual check -// string), but no valid match, return an empty string and set the position to -// resume searching from. If no partial matches are found, return an empty -// string and the location will be StringRef::npos. If one prefix is a substring -// of another, the maximal match should be found. e.g. if "A" and "AA" are -// prefixes then AA-CHECK: should match the second one. -static StringRef FindFirstCandidateMatch(StringRef &Buffer, - Check::CheckType &CheckTy, - size_t &CheckLoc) { - StringRef FirstPrefix; - size_t FirstLoc = StringRef::npos; - size_t SearchLoc = StringRef::npos; - Check::CheckType FirstTy = Check::CheckNone; - - CheckTy = Check::CheckNone; - CheckLoc = StringRef::npos; - - for (StringRef Prefix : CheckPrefixes) { - size_t PrefixLoc = Buffer.find(Prefix); - - if (PrefixLoc == StringRef::npos) - continue; - - // Track where we are searching for invalid prefixes that look almost right. - // We need to only advance to the first partial match on the next attempt - // since a partial match could be a substring of a later, valid prefix. - // Need to skip to the end of the word, otherwise we could end up - // matching a prefix in a substring later. - if (PrefixLoc < SearchLoc) - SearchLoc = SkipWord(Buffer, PrefixLoc); - - // We only want to find the first match to avoid skipping some. - if (PrefixLoc > FirstLoc) - continue; - // If one matching check-prefix is a prefix of another, choose the - // longer one. - if (PrefixLoc == FirstLoc && Prefix.size() < FirstPrefix.size()) - continue; - - StringRef Rest = Buffer.drop_front(PrefixLoc); - // Make sure we have actually found the prefix, and not a word containing - // it. This should also prevent matching the wrong prefix when one is a - // substring of another. - if (PrefixLoc != 0 && IsPartOfWord(Buffer[PrefixLoc - 1])) - FirstTy = Check::CheckNone; - else - FirstTy = FindCheckType(Rest, Prefix); - - FirstLoc = PrefixLoc; - FirstPrefix = Prefix; - } - - // If the first prefix is invalid, we should continue the search after it. - if (FirstTy == Check::CheckNone) { - CheckLoc = SearchLoc; - return ""; - } - - CheckTy = FirstTy; - CheckLoc = FirstLoc; - return FirstPrefix; -} - -static StringRef FindFirstMatchingPrefix(StringRef &Buffer, +/// Search the buffer for the first prefix in the prefix regular expression. +/// +/// This searches the buffer using the provided regular expression, however it +/// enforces constraints beyond that: +/// 1) The found prefix must not be a suffix of something that looks like +/// a valid prefix. +/// 2) The found prefix must be followed by a valid check type suffix using \c +/// FindCheckType above. +/// +/// The first match of the regular expression to satisfy these two is returned, +/// otherwise an empty StringRef is returned to indicate failure. +/// +/// If this routine returns a valid prefix, it will also shrink \p Buffer to +/// start at the beginning of the returned prefix, increment \p LineNumber for +/// each new line consumed from \p Buffer, and set \p CheckTy to the type of +/// check found by examining the suffix. +/// +/// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy +/// is unspecified. +static StringRef FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer, unsigned &LineNumber, - Check::CheckType &CheckTy, - size_t &CheckLoc) { - while (!Buffer.empty()) { - StringRef Prefix = FindFirstCandidateMatch(Buffer, CheckTy, CheckLoc); - // If we found a real match, we are done. - if (!Prefix.empty()) { - LineNumber += Buffer.substr(0, CheckLoc).count('\n'); - return Prefix; - } + Check::CheckType &CheckTy) { + SmallVector<StringRef, 2> Matches; - // We didn't find any almost matches either, we are also done. - if (CheckLoc == StringRef::npos) + while (!Buffer.empty()) { + // Find the first (longest) match using the RE. + if (!PrefixRE.match(Buffer, &Matches)) + // No match at all, bail. return StringRef(); - LineNumber += Buffer.substr(0, CheckLoc + 1).count('\n'); + StringRef Prefix = Matches[0]; + Matches.clear(); + + assert(Prefix.data() >= Buffer.data() && + Prefix.data() < Buffer.data() + Buffer.size() && + "Prefix doesn't start inside of buffer!"); + size_t Loc = Prefix.data() - Buffer.data(); + StringRef Skipped = Buffer.substr(0, Loc); + Buffer = Buffer.drop_front(Loc); + LineNumber += Skipped.count('\n'); + + // Check that the matched prefix isn't a suffix of some other check-like + // word. + // FIXME: This is a very ad-hoc check. it would be better handled in some + // other way. Among other things it seems hard to distinguish between + // intentional and unintentional uses of this feature. + if (Skipped.empty() || !IsPartOfWord(Skipped.back())) { + // Now extract the type. + CheckTy = FindCheckType(Buffer, Prefix); + + // If we've found a valid check type for this prefix, we're done. + if (CheckTy != Check::CheckNone) + return Prefix; + } - // Advance to the last possible match we found and try again. - Buffer = Buffer.drop_front(CheckLoc + 1); + // If we didn't successfully find a prefix, we need to skip this invalid + // prefix and continue scanning. We directly skip the prefix that was + // matched and any additional parts of that check-like word. + Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size())); } + // We ran out of buffer while skipping partial matches so give up. return StringRef(); } -/// ReadCheckFile - Read the check file, which specifies the sequence of -/// expected strings. The strings are added to the CheckStrings vector. -/// Returns true in case of an error, false otherwise. -static bool ReadCheckFile(SourceMgr &SM, +/// Read the check file, which specifies the sequence of expected strings. +/// +/// The strings are added to the CheckStrings vector. Returns true in case of +/// an error, false otherwise. +static bool ReadCheckFile(SourceMgr &SM, StringRef Buffer, Regex &PrefixRE, std::vector<CheckString> &CheckStrings) { - ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = - MemoryBuffer::getFileOrSTDIN(CheckFilename); - if (std::error_code EC = FileOrErr.getError()) { - errs() << "Could not open check file '" << CheckFilename - << "': " << EC.message() << '\n'; - return true; - } - - // If we want to canonicalize whitespace, strip excess whitespace from the - // buffer containing the CHECK lines. Remove DOS style line endings. - std::unique_ptr<MemoryBuffer> F = CanonicalizeInputFile( - std::move(FileOrErr.get()), NoCanonicalizeWhiteSpace); - - // Find all instances of CheckPrefix followed by : in the file. - StringRef Buffer = F->getBuffer(); - - SM.AddNewSourceBuffer(std::move(F), SMLoc()); - std::vector<Pattern> ImplicitNegativeChecks; for (const auto &PatternString : ImplicitCheckNot) { // Create a buffer with fake command line content in order to display the @@ -901,7 +834,6 @@ static bool ReadCheckFile(SourceMgr &SM, "IMPLICIT-CHECK", SM, 0); } - std::vector<Pattern> DagNotMatches = ImplicitNegativeChecks; // LineNumber keeps track of the line on which CheckPrefix instances are @@ -910,35 +842,33 @@ static bool ReadCheckFile(SourceMgr &SM, while (1) { Check::CheckType CheckTy; - size_t PrefixLoc; // See if a prefix occurs in the memory buffer. - StringRef UsedPrefix = FindFirstMatchingPrefix(Buffer, - LineNumber, - CheckTy, - PrefixLoc); + StringRef UsedPrefix = FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, + CheckTy); if (UsedPrefix.empty()) break; - - Buffer = Buffer.drop_front(PrefixLoc); + assert(UsedPrefix.data() == Buffer.data() && + "Failed to move Buffer's start forward, or pointed prefix outside " + "of the buffer!"); // Location to use for error messages. - const char *UsedPrefixStart = Buffer.data() + (PrefixLoc == 0 ? 0 : 1); + const char *UsedPrefixStart = UsedPrefix.data(); - // PrefixLoc is to the start of the prefix. Skip to the end. + // Skip the buffer to the end. Buffer = Buffer.drop_front(UsedPrefix.size() + CheckTypeSize(CheckTy)); // Complain about useful-looking but unsupported suffixes. if (CheckTy == Check::CheckBadNot) { - SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), - SourceMgr::DK_Error, + SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error, "unsupported -NOT combo on prefix '" + UsedPrefix + "'"); return true; } // Okay, we found the prefix, yay. Remember the rest of the line, but ignore - // leading and trailing whitespace. - Buffer = Buffer.substr(Buffer.find_first_not_of(" \t")); + // leading whitespace. + if (!(NoCanonicalizeWhiteSpace && MatchFullLines)) + Buffer = Buffer.substr(Buffer.find_first_not_of(" \t")); // Scan ahead to the end of line. size_t EOL = Buffer.find_first_of("\n\r"); @@ -953,10 +883,10 @@ static bool ReadCheckFile(SourceMgr &SM, // Verify that CHECK-LABEL lines do not define or use variables if ((CheckTy == Check::CheckLabel) && P.hasVariable()) { - SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart), - SourceMgr::DK_Error, - "found '" + UsedPrefix + "-LABEL:'" - " with variable definition or use"); + SM.PrintMessage( + SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error, + "found '" + UsedPrefix + "-LABEL:'" + " with variable definition or use"); return true; } @@ -968,8 +898,8 @@ static bool ReadCheckFile(SourceMgr &SM, StringRef Type = CheckTy == Check::CheckNext ? "NEXT" : "SAME"; SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error, - "found '" + UsedPrefix + "-" + Type + "' without previous '" - + UsedPrefix + ": line"); + "found '" + UsedPrefix + "-" + Type + + "' without previous '" + UsedPrefix + ": line"); return true; } @@ -1012,8 +942,8 @@ static bool ReadCheckFile(SourceMgr &SM, return false; } -static void PrintCheckFailed(const SourceMgr &SM, SMLoc Loc, - const Pattern &Pat, StringRef Buffer, +static void PrintCheckFailed(const SourceMgr &SM, SMLoc Loc, const Pattern &Pat, + StringRef Buffer, StringMap<StringRef> &VariableTable) { // Otherwise, we have an error, emit an error message. SM.PrintMessage(Loc, SourceMgr::DK_Error, @@ -1036,21 +966,20 @@ static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr, PrintCheckFailed(SM, CheckStr.Loc, CheckStr.Pat, Buffer, VariableTable); } -/// CountNumNewlinesBetween - Count the number of newlines in the specified -/// range. +/// Count the number of newlines in the specified range. static unsigned CountNumNewlinesBetween(StringRef Range, const char *&FirstNewLine) { unsigned NumNewLines = 0; while (1) { // Scan for newline. Range = Range.substr(Range.find_first_of("\n\r")); - if (Range.empty()) return NumNewLines; + if (Range.empty()) + return NumNewLines; ++NumNewLines; // Handle \n\r and \r\n as a single newline. - if (Range.size() > 1 && - (Range[1] == '\n' || Range[1] == '\r') && + if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') && (Range[0] != Range[1])) Range = Range.substr(1); Range = Range.substr(1); @@ -1060,6 +989,7 @@ static unsigned CountNumNewlinesBetween(StringRef Range, } } +/// Match check string and its "not strings" and/or "dag strings". size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode, size_t &MatchLen, StringMap<StringRef> &VariableTable) const { @@ -1109,35 +1039,37 @@ size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer, return LastPos + MatchPos; } +/// Verify there is a single line in the given buffer. bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const { if (Pat.getCheckTy() != Check::CheckNext) return false; // Count the number of newlines between the previous match and this one. assert(Buffer.data() != - SM.getMemoryBuffer( - SM.FindBufferContainingLoc( - SMLoc::getFromPointer(Buffer.data())))->getBufferStart() && + SM.getMemoryBuffer(SM.FindBufferContainingLoc( + SMLoc::getFromPointer(Buffer.data()))) + ->getBufferStart() && "CHECK-NEXT can't be the first check in a file"); const char *FirstNewLine = nullptr; unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine); if (NumNewLines == 0) { - SM.PrintMessage(Loc, SourceMgr::DK_Error, Prefix + - "-NEXT: is on the same line as previous match"); - SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), - SourceMgr::DK_Note, "'next' match was here"); + SM.PrintMessage(Loc, SourceMgr::DK_Error, + Prefix + "-NEXT: is on the same line as previous match"); + SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note, + "'next' match was here"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, "previous match ended here"); return true; } if (NumNewLines != 1) { - SM.PrintMessage(Loc, SourceMgr::DK_Error, Prefix + - "-NEXT: is not on the line after the previous match"); - SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), - SourceMgr::DK_Note, "'next' match was here"); + SM.PrintMessage(Loc, SourceMgr::DK_Error, + Prefix + + "-NEXT: is not on the line after the previous match"); + SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note, + "'next' match was here"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, "previous match ended here"); SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note, @@ -1148,6 +1080,7 @@ bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const { return false; } +/// Verify there is no newline in the given buffer. bool CheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const { if (Pat.getCheckTy() != Check::CheckSame) return false; @@ -1176,6 +1109,7 @@ bool CheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const { return false; } +/// Verify there's no "not strings" in the given buffer. bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer, const std::vector<const Pattern *> &NotStrings, StringMap<StringRef> &VariableTable) const { @@ -1185,11 +1119,11 @@ bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer, size_t MatchLen = 0; size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable); - if (Pos == StringRef::npos) continue; + if (Pos == StringRef::npos) + continue; - SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos), - SourceMgr::DK_Error, - Prefix + "-NOT: string occurred!"); + SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Pos), + SourceMgr::DK_Error, Prefix + "-NOT: string occurred!"); SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note, Prefix + "-NOT: pattern specified here"); return true; @@ -1198,6 +1132,7 @@ bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer, return false; } +/// Match "dag strings" and their mixed "not strings". size_t CheckString::CheckDag(const SourceMgr &SM, StringRef Buffer, std::vector<const Pattern *> &NotStrings, StringMap<StringRef> &VariableTable) const { @@ -1239,17 +1174,17 @@ size_t CheckString::CheckDag(const SourceMgr &SM, StringRef Buffer, SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + MatchPos), SourceMgr::DK_Error, Prefix + "-DAG: found a match of CHECK-DAG" - " reordering across a CHECK-NOT"); + " reordering across a CHECK-NOT"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + LastPos), SourceMgr::DK_Note, Prefix + "-DAG: the farthest match of CHECK-DAG" - " is found here"); + " is found here"); SM.PrintMessage(NotStrings[0]->getLoc(), SourceMgr::DK_Note, Prefix + "-NOT: the crossed pattern specified" - " here"); + " here"); SM.PrintMessage(Pat.getLoc(), SourceMgr::DK_Note, Prefix + "-DAG: the reordered pattern specified" - " here"); + " here"); return StringRef::npos; } // All subsequent CHECK-DAGs should be matched from the farthest @@ -1296,11 +1231,28 @@ static bool ValidateCheckPrefixes() { return true; } -// I don't think there's a way to specify an initial value for cl::list, -// so if nothing was specified, add the default -static void AddCheckPrefixIfNeeded() { +// Combines the check prefixes into a single regex so that we can efficiently +// scan for any of the set. +// +// The semantics are that the longest-match wins which matches our regex +// library. +static Regex buildCheckPrefixRegex() { + // I don't think there's a way to specify an initial value for cl::list, + // so if nothing was specified, add the default if (CheckPrefixes.empty()) CheckPrefixes.push_back("CHECK"); + + // We already validated the contents of CheckPrefixes so just concatenate + // them as alternatives. + SmallString<32> PrefixRegexStr; + for (StringRef Prefix : CheckPrefixes) { + if (Prefix != CheckPrefixes.front()) + PrefixRegexStr.push_back('|'); + + PrefixRegexStr.append(Prefix); + } + + return Regex(PrefixRegexStr); } static void DumpCommandLine(int argc, char **argv) { @@ -1310,61 +1262,18 @@ static void DumpCommandLine(int argc, char **argv) { errs() << "\n"; } -int main(int argc, char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); - PrettyStackTraceProgram X(argc, argv); - cl::ParseCommandLineOptions(argc, argv); - - if (!ValidateCheckPrefixes()) { - errs() << "Supplied check-prefix is invalid! Prefixes must be unique and " - "start with a letter and contain only alphanumeric characters, " - "hyphens and underscores\n"; - return 2; - } - - AddCheckPrefixIfNeeded(); - - SourceMgr SM; - - // Read the expected strings from the check file. - std::vector<CheckString> CheckStrings; - if (ReadCheckFile(SM, CheckStrings)) - return 2; - - // Open the file to check and add it to SourceMgr. - ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = - MemoryBuffer::getFileOrSTDIN(InputFilename); - if (std::error_code EC = FileOrErr.getError()) { - errs() << "Could not open input file '" << InputFilename - << "': " << EC.message() << '\n'; - return 2; - } - std::unique_ptr<MemoryBuffer> &File = FileOrErr.get(); - - if (File->getBufferSize() == 0 && !AllowEmptyInput) { - errs() << "FileCheck error: '" << InputFilename << "' is empty.\n"; - DumpCommandLine(argc, argv); - return 2; - } - - // Remove duplicate spaces in the input file if requested. - // Remove DOS style line endings. - std::unique_ptr<MemoryBuffer> F = - CanonicalizeInputFile(std::move(File), NoCanonicalizeWhiteSpace); - - // Check that we have all of the expected strings, in order, in the input - // file. - StringRef Buffer = F->getBuffer(); - - SM.AddNewSourceBuffer(std::move(F), SMLoc()); +/// Check the input to FileCheck provided in the \p Buffer against the \p +/// CheckStrings read from the check file. +/// +/// Returns false if the input fails to satisfy the checks. +bool CheckInput(SourceMgr &SM, StringRef Buffer, + ArrayRef<CheckString> CheckStrings) { + bool ChecksFailed = false; /// VariableTable - This holds all the current filecheck variables. StringMap<StringRef> VariableTable; - bool hasError = false; - unsigned i = 0, j = 0, e = CheckStrings.size(); - while (true) { StringRef CheckRegion; if (j == e) { @@ -1378,29 +1287,28 @@ int main(int argc, char **argv) { // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG size_t MatchLabelLen = 0; - size_t MatchLabelPos = CheckLabelStr.Check(SM, Buffer, true, - MatchLabelLen, VariableTable); - if (MatchLabelPos == StringRef::npos) { - hasError = true; - break; - } + size_t MatchLabelPos = + CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, VariableTable); + if (MatchLabelPos == StringRef::npos) + // Immediately bail of CHECK-LABEL fails, nothing else we can do. + return false; CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen); Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen); ++j; } - for ( ; i != j; ++i) { + for (; i != j; ++i) { const CheckString &CheckStr = CheckStrings[i]; // Check each string within the scanned region, including a second check // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG) size_t MatchLen = 0; - size_t MatchPos = CheckStr.Check(SM, CheckRegion, false, MatchLen, - VariableTable); + size_t MatchPos = + CheckStr.Check(SM, CheckRegion, false, MatchLen, VariableTable); if (MatchPos == StringRef::npos) { - hasError = true; + ChecksFailed = true; i = j; break; } @@ -1412,5 +1320,78 @@ int main(int argc, char **argv) { break; } - return hasError ? 1 : 0; + // Success if no checks failed. + return !ChecksFailed; +} + +int main(int argc, char **argv) { + sys::PrintStackTraceOnErrorSignal(argv[0]); + PrettyStackTraceProgram X(argc, argv); + cl::ParseCommandLineOptions(argc, argv); + + if (!ValidateCheckPrefixes()) { + errs() << "Supplied check-prefix is invalid! Prefixes must be unique and " + "start with a letter and contain only alphanumeric characters, " + "hyphens and underscores\n"; + return 2; + } + + Regex PrefixRE = buildCheckPrefixRegex(); + std::string REError; + if (!PrefixRE.isValid(REError)) { + errs() << "Unable to combine check-prefix strings into a prefix regular " + "expression! This is likely a bug in FileCheck's verification of " + "the check-prefix strings. Regular expression parsing failed " + "with the following error: " + << REError << "\n"; + return 2; + } + + SourceMgr SM; + + // Read the expected strings from the check file. + ErrorOr<std::unique_ptr<MemoryBuffer>> CheckFileOrErr = + MemoryBuffer::getFileOrSTDIN(CheckFilename); + if (std::error_code EC = CheckFileOrErr.getError()) { + errs() << "Could not open check file '" << CheckFilename + << "': " << EC.message() << '\n'; + return 2; + } + MemoryBuffer &CheckFile = *CheckFileOrErr.get(); + + SmallString<4096> CheckFileBuffer; + StringRef CheckFileText = CanonicalizeFile(CheckFile, CheckFileBuffer); + + SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer( + CheckFileText, CheckFile.getBufferIdentifier()), + SMLoc()); + + std::vector<CheckString> CheckStrings; + if (ReadCheckFile(SM, CheckFileText, PrefixRE, CheckStrings)) + return 2; + + // Open the file to check and add it to SourceMgr. + ErrorOr<std::unique_ptr<MemoryBuffer>> InputFileOrErr = + MemoryBuffer::getFileOrSTDIN(InputFilename); + if (std::error_code EC = InputFileOrErr.getError()) { + errs() << "Could not open input file '" << InputFilename + << "': " << EC.message() << '\n'; + return 2; + } + MemoryBuffer &InputFile = *InputFileOrErr.get(); + + if (InputFile.getBufferSize() == 0 && !AllowEmptyInput) { + errs() << "FileCheck error: '" << InputFilename << "' is empty.\n"; + DumpCommandLine(argc, argv); + return 2; + } + + SmallString<4096> InputFileBuffer; + StringRef InputFileText = CanonicalizeFile(InputFile, InputFileBuffer); + + SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer( + InputFileText, InputFile.getBufferIdentifier()), + SMLoc()); + + return CheckInput(SM, InputFileText, CheckStrings) ? EXIT_SUCCESS : 1; } diff --git a/gnu/llvm/utils/KillTheDoctor/CMakeLists.txt b/gnu/llvm/utils/KillTheDoctor/CMakeLists.txt index 37c2b7ceb46..72d994fb995 100644 --- a/gnu/llvm/utils/KillTheDoctor/CMakeLists.txt +++ b/gnu/llvm/utils/KillTheDoctor/CMakeLists.txt @@ -2,4 +2,7 @@ add_llvm_utility(KillTheDoctor KillTheDoctor.cpp ) -target_link_libraries(KillTheDoctor LLVMSupport) +target_link_libraries(KillTheDoctor + LLVMSupport + psapi + ) diff --git a/gnu/llvm/utils/KillTheDoctor/KillTheDoctor.cpp b/gnu/llvm/utils/KillTheDoctor/KillTheDoctor.cpp index c9e96617f37..19c880ae94d 100644 --- a/gnu/llvm/utils/KillTheDoctor/KillTheDoctor.cpp +++ b/gnu/llvm/utils/KillTheDoctor/KillTheDoctor.cpp @@ -52,9 +52,9 @@ #include <system_error> // These includes must be last. -#include <Windows.h> -#include <WinError.h> -#include <Dbghelp.h> +#include <windows.h> +#include <winerror.h> +#include <dbghelp.h> #include <psapi.h> using namespace llvm; @@ -349,7 +349,7 @@ int main(int argc, char **argv) { ::_set_error_mode(_OUT_TO_STDERR); BOOL success = ::CreateProcessA(ProgramToRun.c_str(), - LPSTR(CommandLine.c_str()), + const_cast<LPSTR>(CommandLine.c_str()), NULL, NULL, FALSE, diff --git a/gnu/llvm/utils/LLVMVisualizers/llvm.natvis b/gnu/llvm/utils/LLVMVisualizers/llvm.natvis index 6d8475a1c72..439868a5afd 100644 --- a/gnu/llvm/utils/LLVMVisualizers/llvm.natvis +++ b/gnu/llvm/utils/LLVMVisualizers/llvm.natvis @@ -56,8 +56,8 @@ For later versions of Visual Studio, no setup is required. </Expand>
</Type>
<Type Name="llvm::SmallString<*>">
- <DisplayString>{BeginX,s}</DisplayString>
- <StringView>BeginX,s</StringView>
+ <DisplayString>{(const char*)BeginX,[(char*)EndX - (char*)BeginX] na}</DisplayString>
+ <StringView>(const char*)BeginX,[(char*)EndX - (char*)BeginX]</StringView>
<Expand>
<Item Name="[size]">(char*)EndX - (char*)BeginX</Item>
<Item Name="[capacity]">(char*)CapacityX - (char*)BeginX</Item>
diff --git a/gnu/llvm/utils/TableGen/AsmMatcherEmitter.cpp b/gnu/llvm/utils/TableGen/AsmMatcherEmitter.cpp index 76228e0b658..1272d2b9f28 100644 --- a/gnu/llvm/utils/TableGen/AsmMatcherEmitter.cpp +++ b/gnu/llvm/utils/TableGen/AsmMatcherEmitter.cpp @@ -97,6 +97,9 @@ //===----------------------------------------------------------------------===// #include "CodeGenTarget.h" +#include "SubtargetFeatureInfo.h" +#include "Types.h" +#include "llvm/ADT/CachedHashString.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" @@ -126,7 +129,6 @@ MatchPrefix("match-prefix", cl::init(""), namespace { class AsmMatcherInfo; -struct SubtargetFeatureInfo; // Register sets are used as keys in some second-order sets TableGen creates // when generating its data structures. This means that the order of two @@ -353,6 +355,7 @@ public: std::string TokenizingCharacters; std::string SeparatorCharacters; std::string BreakCharacters; + std::string Name; int AsmVariantNo; }; @@ -556,20 +559,17 @@ struct MatchableInfo { /// findAsmOperand - Find the AsmOperand with the specified name and /// suboperand index. int findAsmOperand(StringRef N, int SubOpIdx) const { - auto I = std::find_if(AsmOperands.begin(), AsmOperands.end(), - [&](const AsmOperand &Op) { - return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx; - }); + auto I = find_if(AsmOperands, [&](const AsmOperand &Op) { + return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx; + }); return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1; } /// findAsmOperandNamed - Find the first AsmOperand with the specified name. /// This does not check the suboperand index. int findAsmOperandNamed(StringRef N) const { - auto I = std::find_if(AsmOperands.begin(), AsmOperands.end(), - [&](const AsmOperand &Op) { - return Op.SrcOpName == N; - }); + auto I = find_if(AsmOperands, + [&](const AsmOperand &Op) { return Op.SrcOpName == N; }); return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1; } @@ -653,28 +653,6 @@ private: void addAsmOperand(StringRef Token, bool IsIsolatedToken = false); }; -/// SubtargetFeatureInfo - Helper class for storing information on a subtarget -/// feature which participates in instruction matching. -struct SubtargetFeatureInfo { - /// \brief The predicate record for this feature. - Record *TheDef; - - /// \brief An unique index assigned to represent this feature. - uint64_t Index; - - SubtargetFeatureInfo(Record *D, uint64_t Idx) : TheDef(D), Index(Idx) {} - - /// \brief The name of the enumerated constant identifying this feature. - std::string getEnumName() const { - return "Feature_" + TheDef->getName(); - } - - void dump() const { - errs() << getEnumName() << " " << Index << "\n"; - TheDef->dump(); - } -}; - struct OperandMatchEntry { unsigned OperandMask; const MatchableInfo* MI; @@ -754,7 +732,7 @@ public: CodeGenTarget &Target, RecordKeeper &Records); - /// buildInfo - Construct the various tables used during matching. + /// Construct the various tables used during matching. void buildInfo(); /// buildOperandMatchInfo - Build the necessary information to handle user @@ -774,9 +752,9 @@ public: } bool hasOptionalOperands() const { - return std::find_if(Classes.begin(), Classes.end(), - [](const ClassInfo& Class){ return Class.IsOptional; }) - != Classes.end(); + return find_if(Classes, [](const ClassInfo &Class) { + return Class.IsOptional; + }) != Classes.end(); } }; @@ -1311,10 +1289,10 @@ buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) { if (CI->ValueName.empty()) { CI->ClassName = Rec->getName(); - CI->Name = "MCK_" + Rec->getName(); + CI->Name = "MCK_" + Rec->getName().str(); CI->ValueName = Rec->getName(); } else - CI->ValueName = CI->ValueName + "," + Rec->getName(); + CI->ValueName = CI->ValueName + "," + Rec->getName().str(); } } @@ -1437,21 +1415,15 @@ void AsmMatcherInfo::buildOperandMatchInfo() { void AsmMatcherInfo::buildInfo() { // Build information about all of the AssemblerPredicates. - std::vector<Record*> AllPredicates = - Records.getAllDerivedDefinitions("Predicate"); - for (Record *Pred : AllPredicates) { - // Ignore predicates that are not intended for the assembler. - if (!Pred->getValueAsBit("AssemblerMatcherPredicate")) - continue; - - if (Pred->getName().empty()) - PrintFatalError(Pred->getLoc(), "Predicate has no name!"); - - SubtargetFeatures.insert(std::make_pair( - Pred, SubtargetFeatureInfo(Pred, SubtargetFeatures.size()))); - DEBUG(SubtargetFeatures.find(Pred)->second.dump()); - assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!"); - } + const std::vector<std::pair<Record *, SubtargetFeatureInfo>> + &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records); + SubtargetFeatures.insert(SubtargetFeaturePairs.begin(), + SubtargetFeaturePairs.end()); +#ifndef NDEBUG + for (const auto &Pair : SubtargetFeatures) + DEBUG(Pair.second.dump()); +#endif // NDEBUG + assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!"); bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst"); @@ -1471,6 +1443,7 @@ void AsmMatcherInfo::buildInfo() { AsmVariant->getValueAsString("SeparatorCharacters"); Variant.BreakCharacters = AsmVariant->getValueAsString("BreakCharacters"); + Variant.Name = AsmVariant->getValueAsString("Name"); Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant"); for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) { @@ -1484,6 +1457,11 @@ void AsmMatcherInfo::buildInfo() { if (CGI->TheDef->getValueAsBit("isCodeGenOnly")) continue; + // Ignore instructions for different instructions + const std::string V = CGI->TheDef->getValueAsString("AsmVariantName"); + if (!V.empty() && V != Variant.Name) + continue; + auto II = llvm::make_unique<MatchableInfo>(*CGI); II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst); @@ -1512,6 +1490,10 @@ void AsmMatcherInfo::buildInfo() { .startswith( MatchPrefix)) continue; + const std::string V = Alias->TheDef->getValueAsString("AsmVariantName"); + if (!V.empty() && V != Variant.Name) + continue; + auto II = llvm::make_unique<MatchableInfo>(std::move(Alias)); II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst); @@ -1613,15 +1595,15 @@ void AsmMatcherInfo::buildInfo() { // Reorder classes so that classes precede super classes. Classes.sort(); -#ifndef NDEBUG - // Verify that the table is now sorted +#ifdef EXPENSIVE_CHECKS + // Verify that the table is sorted and operator < works transitively. for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) { for (auto J = I; J != E; ++J) { assert(!(*J < *I)); assert(I == J || !J->isSubsetOf(*I)); } } -#endif // NDEBUG +#endif } /// buildInstructionOperandReference - The specified operand is a reference to a @@ -1814,13 +1796,13 @@ void MatchableInfo::buildAliasResultOperands() { } } -static unsigned getConverterOperandID(const std::string &Name, - SmallSetVector<std::string, 16> &Table, - bool &IsNew) { - IsNew = Table.insert(Name); +static unsigned +getConverterOperandID(const std::string &Name, + SmallSetVector<CachedHashString, 16> &Table, + bool &IsNew) { + IsNew = Table.insert(CachedHashString(Name)); - unsigned ID = IsNew ? Table.size() - 1 : - std::find(Table.begin(), Table.end(), Name) - Table.begin(); + unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin(); assert(ID < Table.size()); @@ -1831,13 +1813,13 @@ static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName, std::vector<std::unique_ptr<MatchableInfo>> &Infos, bool HasMnemonicFirst, bool HasOptionalOperands, raw_ostream &OS) { - SmallSetVector<std::string, 16> OperandConversionKinds; - SmallSetVector<std::string, 16> InstructionConversionKinds; + SmallSetVector<CachedHashString, 16> OperandConversionKinds; + SmallSetVector<CachedHashString, 16> InstructionConversionKinds; std::vector<std::vector<uint8_t> > ConversionTable; size_t MaxRowLength = 2; // minimum is custom converter plus terminator. // TargetOperandClass - This is the target's operand class, like X86Operand. - std::string TargetOperandClass = Target.getName() + "Operand"; + std::string TargetOperandClass = Target.getName().str() + "Operand"; // Write the convert function to a separate stream, so we can drop it after // the enum. We'll build up the conversion handlers for the individual @@ -1904,9 +1886,9 @@ static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName, // Pre-populate the operand conversion kinds with the standard always // available entries. - OperandConversionKinds.insert("CVT_Done"); - OperandConversionKinds.insert("CVT_Reg"); - OperandConversionKinds.insert("CVT_Tied"); + OperandConversionKinds.insert(CachedHashString("CVT_Done")); + OperandConversionKinds.insert(CachedHashString("CVT_Reg")); + OperandConversionKinds.insert(CachedHashString("CVT_Tied")); enum { CVT_Done, CVT_Reg, CVT_Tied }; for (auto &II : Infos) { @@ -1918,13 +1900,13 @@ static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName, II->ConversionFnKind = Signature; // Check if we have already generated this signature. - if (!InstructionConversionKinds.insert(Signature)) + if (!InstructionConversionKinds.insert(CachedHashString(Signature))) continue; // Remember this converter for the kind enum. unsigned KindID = OperandConversionKinds.size(); - OperandConversionKinds.insert("CVT_" + - getEnumNameForToken(AsmMatchConverter)); + OperandConversionKinds.insert( + CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter))); // Add the converter row for this instruction. ConversionTable.emplace_back(); @@ -2072,7 +2054,7 @@ static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName, Reg = "0"; } else { Reg = getQualifiedName(OpInfo.Register); - Name = "reg" + OpInfo.Register->getName(); + Name = "reg" + OpInfo.Register->getName().str(); } Signature += "__" + Name; Name = "CVT_" + Name; @@ -2106,7 +2088,7 @@ static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName, // Save the signature. If we already have it, don't add a new row // to the table. - if (!InstructionConversionKinds.insert(Signature)) + if (!InstructionConversionKinds.insert(CachedHashString(Signature))) continue; // Add the row to the table. @@ -2123,14 +2105,14 @@ static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName, // Output the operand conversion kind enum. OS << "enum OperatorConversionKind {\n"; - for (const std::string &Converter : OperandConversionKinds) + for (const auto &Converter : OperandConversionKinds) OS << " " << Converter << ",\n"; OS << " CVT_NUM_CONVERTERS\n"; OS << "};\n\n"; // Output the instruction conversion kind enum. OS << "enum InstructionConversionKind {\n"; - for (const std::string &Signature : InstructionConversionKinds) + for (const auto &Signature : InstructionConversionKinds) OS << " " << Signature << ",\n"; OS << " CVT_NUM_SIGNATURES\n"; OS << "};\n\n"; @@ -2382,40 +2364,6 @@ static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser, OS << "}\n\n"; } -static const char *getMinimalTypeForRange(uint64_t Range) { - assert(Range <= 0xFFFFFFFFFFFFFFFFULL && "Enum too large"); - if (Range > 0xFFFFFFFFULL) - return "uint64_t"; - if (Range > 0xFFFF) - return "uint32_t"; - if (Range > 0xFF) - return "uint16_t"; - return "uint8_t"; -} - -static const char *getMinimalRequiredFeaturesType(const AsmMatcherInfo &Info) { - uint64_t MaxIndex = Info.SubtargetFeatures.size(); - if (MaxIndex > 0) - MaxIndex--; - return getMinimalTypeForRange(1ULL << MaxIndex); -} - -/// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag -/// definitions. -static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info, - raw_ostream &OS) { - OS << "// Flags for subtarget features that participate in " - << "instruction matching.\n"; - OS << "enum SubtargetFeatureFlag : " << getMinimalRequiredFeaturesType(Info) - << " {\n"; - for (const auto &SF : Info.SubtargetFeatures) { - const SubtargetFeatureInfo &SFI = SF.second; - OS << " " << SFI.getEnumName() << " = (1ULL << " << SFI.Index << "),\n"; - } - OS << " Feature_None = 0\n"; - OS << "};\n\n"; -} - /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types. static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) { // Get the set of diagnostic types from all of the operand classes. @@ -2456,55 +2404,6 @@ static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) { OS << "}\n\n"; } -/// emitComputeAvailableFeatures - Emit the function to compute the list of -/// available features given a subtarget. -static void emitComputeAvailableFeatures(AsmMatcherInfo &Info, - raw_ostream &OS) { - std::string ClassName = - Info.AsmParser->getValueAsString("AsmParserClassName"); - - OS << "uint64_t " << Info.Target.getName() << ClassName << "::\n" - << "ComputeAvailableFeatures(const FeatureBitset& FB) const {\n"; - OS << " uint64_t Features = 0;\n"; - for (const auto &SF : Info.SubtargetFeatures) { - const SubtargetFeatureInfo &SFI = SF.second; - - OS << " if ("; - std::string CondStorage = - SFI.TheDef->getValueAsString("AssemblerCondString"); - StringRef Conds = CondStorage; - std::pair<StringRef,StringRef> Comma = Conds.split(','); - bool First = true; - do { - if (!First) - OS << " && "; - - bool Neg = false; - StringRef Cond = Comma.first; - if (Cond[0] == '!') { - Neg = true; - Cond = Cond.substr(1); - } - - OS << "("; - if (Neg) - OS << "!"; - OS << "FB[" << Info.Target.getName() << "::" << Cond << "])"; - - if (Comma.second.empty()) - break; - - First = false; - Comma = Comma.second.split(','); - } while (true); - - OS << ")\n"; - OS << " Features |= " << SFI.getEnumName() << ";\n"; - } - OS << " return Features;\n"; - OS << "}\n\n"; -} - static std::string GetAliasRequiredFeatures(Record *R, const AsmMatcherInfo &Info) { std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates"); @@ -2646,7 +2545,7 @@ static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target, // Emit the static custom operand parsing table; OS << "namespace {\n"; OS << " struct OperandMatchEntry {\n"; - OS << " " << getMinimalRequiredFeaturesType(Info) + OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size()) << " RequiredFeatures;\n"; OS << " " << getMinimalTypeForRange(MaxMnemonicIndex) << " Mnemonic;\n"; @@ -2719,8 +2618,7 @@ static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target, // Emit the operand class switch to call the correct custom parser for // the found operand class. - OS << Target.getName() << ClassName << "::OperandMatchResultTy " - << Target.getName() << ClassName << "::\n" + OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n" << "tryCustomParseOperand(OperandVector" << " &Operands,\n unsigned MCK) {\n\n" << " switch(MCK) {\n"; @@ -2741,8 +2639,7 @@ static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target, // Emit the static custom operand parser. This code is very similar with // the other matcher. Also use MatchResultTy here just in case we go for // a better error handling. - OS << Target.getName() << ClassName << "::OperandMatchResultTy " - << Target.getName() << ClassName << "::\n" + OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n" << "MatchOperandParserImpl(OperandVector" << " &Operands,\n StringRef Mnemonic) {\n"; @@ -2822,15 +2719,15 @@ void AsmMatcherEmitter::run(raw_ostream &OS) { const std::unique_ptr<MatchableInfo> &b){ return *a < *b;}); -#ifndef NDEBUG - // Verify that the table is now sorted +#ifdef EXPENSIVE_CHECKS + // Verify that the table is sorted and operator < works transitively. for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E; ++I) { for (auto J = I; J != E; ++J) { assert(!(**J < **I)); } } -#endif // NDEBUG +#endif DEBUG_WITH_TYPE("instruction_info", { for (const auto &MI : Info.Matchables) @@ -2896,11 +2793,6 @@ void AsmMatcherEmitter::run(raw_ostream &OS) { << " unsigned VariantID = 0);\n"; if (!Info.OperandMatchInfo.empty()) { - OS << "\n enum OperandMatchResultTy {\n"; - OS << " MatchOperand_Success, // operand matched successfully\n"; - OS << " MatchOperand_NoMatch, // operand did not match\n"; - OS << " MatchOperand_ParseFail // operand matched but had errors\n"; - OS << " };\n"; OS << " OperandMatchResultTy MatchOperandParserImpl(\n"; OS << " OperandVector &Operands,\n"; OS << " StringRef Mnemonic);\n"; @@ -2922,7 +2814,8 @@ void AsmMatcherEmitter::run(raw_ostream &OS) { OS << "#undef GET_REGISTER_MATCHER\n\n"; // Emit the subtarget feature enumeration. - emitSubtargetFeatureFlagEnumeration(Info, OS); + SubtargetFeatureInfo::emitSubtargetFeatureFlagEnumeration( + Info.SubtargetFeatures, OS); // Emit the function to match a register name to number. // This should be omitted for Mips target @@ -2967,7 +2860,9 @@ void AsmMatcherEmitter::run(raw_ostream &OS) { emitValidateOperandClass(Info, OS); // Emit the available features compute function. - emitComputeAvailableFeatures(Info, OS); + SubtargetFeatureInfo::emitComputeAvailableFeatures( + Info.Target.getName(), ClassName, "ComputeAvailableFeatures", + Info.SubtargetFeatures, OS); StringToOffsetTable StringTable; @@ -3005,7 +2900,7 @@ void AsmMatcherEmitter::run(raw_ostream &OS) { OS << " uint16_t Opcode;\n"; OS << " " << getMinimalTypeForRange(Info.Matchables.size()) << " ConvertFn;\n"; - OS << " " << getMinimalRequiredFeaturesType(Info) + OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size()) << " RequiredFeatures;\n"; OS << " " << getMinimalTypeForRange( std::distance(Info.Classes.begin(), Info.Classes.end())) @@ -3254,8 +3149,24 @@ void AsmMatcherEmitter::run(raw_ostream &OS) { OS << " }\n"; OS << "\n"; OS << " Inst.clear();\n\n"; + OS << " Inst.setOpcode(it->Opcode);\n"; + // Verify the instruction with the target-specific match predicate function. + OS << " // We have a potential match but have not rendered the operands.\n" + << " // Check the target predicate to handle any context sensitive\n" + " // constraints.\n" + << " // For example, Ties that are referenced multiple times must be\n" + " // checked here to ensure the input is the same for each match\n" + " // constraints. If we leave it any later the ties will have been\n" + " // canonicalized\n" + << " unsigned MatchResult;\n" + << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, " + "Operands)) != Match_Success) {\n" + << " Inst.clear();\n" + << " RetCode = MatchResult;\n" + << " HadMatchOtherThanPredicate = true;\n" + << " continue;\n" + << " }\n\n"; OS << " if (matchingInlineAsm) {\n"; - OS << " Inst.setOpcode(it->Opcode);\n"; OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n"; OS << " return Match_Success;\n"; OS << " }\n\n"; @@ -3272,7 +3183,6 @@ void AsmMatcherEmitter::run(raw_ostream &OS) { // Verify the instruction with the target-specific match predicate function. OS << " // We have a potential match. Check the target predicate to\n" << " // handle any context sensitive constraints.\n" - << " unsigned MatchResult;\n" << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !=" << " Match_Success) {\n" << " Inst.clear();\n" @@ -3289,7 +3199,9 @@ void AsmMatcherEmitter::run(raw_ostream &OS) { if (HasDeprecation) { OS << " std::string Info;\n"; - OS << " if (MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n"; + OS << " if (!getParser().getTargetParser().\n"; + OS << " getTargetOptions().MCNoDeprecatedWarn &&\n"; + OS << " MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n"; OS << " SMLoc Loc = ((" << Target.getName() << "Operand&)*Operands[0]).getStartLoc();\n"; OS << " getParser().Warning(Loc, Info, None);\n"; diff --git a/gnu/llvm/utils/TableGen/AsmWriterEmitter.cpp b/gnu/llvm/utils/TableGen/AsmWriterEmitter.cpp index fc2138f7e8e..a7c6104aaa2 100644 --- a/gnu/llvm/utils/TableGen/AsmWriterEmitter.cpp +++ b/gnu/llvm/utils/TableGen/AsmWriterEmitter.cpp @@ -13,32 +13,53 @@ //===----------------------------------------------------------------------===// #include "AsmWriterInst.h" +#include "CodeGenInstruction.h" +#include "CodeGenRegisters.h" #include "CodeGenTarget.h" #include "SequenceToOffsetTable.h" +#include "Types.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallString.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" +#include "llvm/Support/Casting.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" #include "llvm/Support/MathExtras.h" +#include "llvm/Support/raw_ostream.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" #include <algorithm> #include <cassert> +#include <cstddef> +#include <cstdint> +#include <deque> +#include <iterator> #include <map> +#include <set> +#include <string> +#include <tuple> #include <utility> #include <vector> + using namespace llvm; #define DEBUG_TYPE "asm-writer-emitter" namespace { + class AsmWriterEmitter { RecordKeeper &Records; CodeGenTarget Target; ArrayRef<const CodeGenInstruction *> NumberedInstructions; std::vector<AsmWriterInst> Instructions; + public: AsmWriterEmitter(RecordKeeper &R); @@ -54,10 +75,11 @@ private: std::vector<unsigned> &InstOpsUsed, bool PassSubtarget) const; }; + } // end anonymous namespace static void PrintCases(std::vector<std::pair<std::string, - AsmWriterOperand> > &OpsToPrint, raw_ostream &O, + AsmWriterOperand>> &OpsToPrint, raw_ostream &O, bool PassSubtarget) { O << " case " << OpsToPrint.back().first << ":"; AsmWriterOperand TheOp = OpsToPrint.back().second; @@ -76,7 +98,6 @@ static void PrintCases(std::vector<std::pair<std::string, O << "\n break;\n"; } - /// EmitInstructions - Emit the last instruction in the vector and any other /// instructions that are suitably similar to it. static void EmitInstructions(std::vector<AsmWriterInst> &Insts, @@ -115,14 +136,14 @@ static void EmitInstructions(std::vector<AsmWriterInst> &Insts, // emit a switch for just this operand now. O << " switch (MI->getOpcode()) {\n"; O << " default: llvm_unreachable(\"Unexpected opcode.\");\n"; - std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint; + std::vector<std::pair<std::string, AsmWriterOperand>> OpsToPrint; OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" + - FirstInst.CGI->TheDef->getName(), + FirstInst.CGI->TheDef->getName().str(), FirstInst.Operands[i])); for (const AsmWriterInst &AWI : SimilarInsts) { - OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+ - AWI.CGI->TheDef->getName(), + OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::" + + AWI.CGI->TheDef->getName().str(), AWI.Operands[i])); } std::reverse(OpsToPrint.begin(), OpsToPrint.end()); @@ -140,7 +161,6 @@ FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands, std::vector<std::vector<unsigned>> &InstIdxs, std::vector<unsigned> &InstOpsUsed, bool PassSubtarget) const { - // This vector parallels UniqueOperandCommands, keeping track of which // instructions each case are used for. It is a comma separated string of // enums. @@ -157,8 +177,7 @@ FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands, // Check to see if we already have 'Command' in UniqueOperandCommands. // If not, add it. - auto I = std::find(UniqueOperandCommands.begin(), - UniqueOperandCommands.end(), Command); + auto I = llvm::find(UniqueOperandCommands, Command); if (I != UniqueOperandCommands.end()) { size_t idx = I - UniqueOperandCommands.begin(); InstrsForCase[idx] += ", "; @@ -225,7 +244,6 @@ FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands, } } - static void UnescapeString(std::string &Str) { for (unsigned i = 0; i != Str.size(); ++i) { if (Str[i] == '\\' && i != Str.size()-1) { @@ -317,7 +335,7 @@ void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) { std::vector<std::vector<std::string>> TableDrivenOperandPrinters; - while (1) { + while (true) { std::vector<std::string> UniqueOperandCommands; std::vector<std::vector<unsigned>> InstIdxs; std::vector<unsigned> NumInstOpsHandled; @@ -451,10 +469,8 @@ void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) { } // Okay, delete instructions with no operand info left. - auto I = std::remove_if(Instructions.begin(), Instructions.end(), - [](AsmWriterInst &Inst) { - return Inst.Operands.empty(); - }); + auto I = llvm::remove_if(Instructions, + [](AsmWriterInst &Inst) { return Inst.Operands.empty(); }); Instructions.erase(I, Instructions.end()); @@ -480,15 +496,6 @@ void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) { O << "}\n"; } -static const char *getMinimalTypeForRange(uint64_t Range) { - assert(Range < 0xFFFFFFFFULL && "Enum too large"); - if (Range > 0xFFFF) - return "uint32_t"; - if (Range > 0xFF) - return "uint16_t"; - return "uint8_t"; -} - static void emitRegisterNameString(raw_ostream &O, StringRef AltName, const std::deque<CodeGenRegister> &Registers) { @@ -533,7 +540,7 @@ emitRegisterNameString(raw_ostream &O, StringRef AltName, StringTable.emit(O, printChar); O << " };\n\n"; - O << " static const " << getMinimalTypeForRange(StringTable.size()-1) + O << " static const " << getMinimalTypeForRange(StringTable.size() - 1, 32) << " RegAsmOffset" << AltName << "[] = {"; for (unsigned i = 0, e = Registers.size(); i != e; ++i) { if ((i % 14) == 0) @@ -595,6 +602,7 @@ void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) { } namespace { + // IAPrinter - Holds information about an InstAlias. Two InstAliases match if // they both have the same conditionals. In which case, we cannot print out the // alias for that pattern. @@ -604,6 +612,7 @@ class IAPrinter { std::string Result; std::string AsmString; + public: IAPrinter(std::string R, std::string AS) : Result(std::move(R)), AsmString(std::move(AS)) {} @@ -725,9 +734,10 @@ static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) { } namespace { + struct AliasPriorityComparator { typedef std::pair<CodeGenInstAlias, int> ValueType; - bool operator()(const ValueType &LHS, const ValueType &RHS) { + bool operator()(const ValueType &LHS, const ValueType &RHS) const { if (LHS.second == RHS.second) { // We don't actually care about the order, but for consistency it // shouldn't depend on pointer comparisons. @@ -738,8 +748,8 @@ struct AliasPriorityComparator { return LHS.second > RHS.second; } }; -} +} // end anonymous namespace void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { Record *AsmWriter = Target.getAsmWriter(); @@ -814,14 +824,14 @@ void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { NumMIOps += Operand.getMINumOperands(); std::string Cond; - Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(NumMIOps); + Cond = std::string("MI->getNumOperands() == ") + utostr(NumMIOps); IAP.addCond(Cond); bool CantHandle = false; unsigned MIOpNum = 0; for (unsigned i = 0, e = LastOpNo; i != e; ++i) { - std::string Op = "MI->getOperand(" + llvm::utostr(MIOpNum) + ")"; + std::string Op = "MI->getOperand(" + utostr(MIOpNum) + ")"; const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i]; @@ -838,9 +848,8 @@ void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { Rec->isSubClassOf("Operand")) { std::string PrintMethod = Rec->getValueAsString("PrintMethod"); if (PrintMethod != "" && PrintMethod != "printOperand") { - PrintMethodIdx = std::find(PrintMethods.begin(), - PrintMethods.end(), PrintMethod) - - PrintMethods.begin(); + PrintMethodIdx = + llvm::find(PrintMethods, PrintMethod) - PrintMethods.begin(); if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size()) PrintMethods.push_back(PrintMethod); } @@ -856,12 +865,12 @@ void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { Record *R = CGA.ResultOperands[i].getRecord(); if (R->isSubClassOf("RegisterOperand")) R = R->getValueAsDef("RegClass"); - Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" + - R->getName() + "RegClassID)" - ".contains(" + Op + ".getReg())"; + Cond = std::string("MRI.getRegClass(") + Target.getName().str() + + "::" + R->getName().str() + "RegClassID).contains(" + Op + + ".getReg())"; } else { Cond = Op + ".getReg() == MI->getOperand(" + - llvm::utostr(IAP.getOpIndex(ROName)) + ").getReg()"; + utostr(IAP.getOpIndex(ROName)) + ").getReg()"; } } else { // Assume all printable operands are desired for now. This can be @@ -878,8 +887,8 @@ void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { } else break; // No conditions on this operand at all } - Cond = Target.getName() + ClassName + "ValidateMCOperand(" + - Op + ", STI, " + llvm::utostr(Entry) + ")"; + Cond = Target.getName().str() + ClassName + "ValidateMCOperand(" + + Op + ", STI, " + utostr(Entry) + ")"; } // for all subcases of ResultOperand::K_Record: IAP.addCond(Cond); @@ -890,8 +899,7 @@ void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { // MCInst will. An MCExpr could be present, for example. IAP.addCond(Op + ".isImm()"); - Cond = Op + ".getImm() == " + - llvm::utostr(CGA.ResultOperands[i].getImm()); + Cond = Op + ".getImm() == " + itostr(CGA.ResultOperands[i].getImm()); IAP.addCond(Cond); break; } @@ -903,8 +911,8 @@ void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { break; } - Cond = Op + ".getReg() == " + Target.getName() + "::" + - CGA.ResultOperands[i].getRegister()->getName(); + Cond = Op + ".getReg() == " + Target.getName().str() + "::" + + CGA.ResultOperands[i].getRegister()->getName().str(); IAP.addCond(Cond); break; } @@ -1112,7 +1120,6 @@ void AsmWriterEmitter::run(raw_ostream &O) { EmitPrintAliasInstruction(O); } - namespace llvm { void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) { @@ -1120,4 +1127,4 @@ void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) { AsmWriterEmitter(RK).run(OS); } -} // End llvm namespace +} // end namespace llvm diff --git a/gnu/llvm/utils/TableGen/Attributes.cpp b/gnu/llvm/utils/TableGen/Attributes.cpp index 58dbe5767ad..927f6e0e5b4 100644 --- a/gnu/llvm/utils/TableGen/Attributes.cpp +++ b/gnu/llvm/utils/TableGen/Attributes.cpp @@ -156,7 +156,7 @@ void Attributes::printStrBoolAttrClasses(raw_ostream &OS, OS << "// StrBoolAttr classes\n"; for (const auto *R : Records) { OS << "struct " << R->getName() << "Attr : StrBoolAttr {\n"; - OS << " static const char *getKind() {\n"; + OS << " static StringRef getKind() {\n"; OS << " return \"" << R->getValueAsString("AttrString") << "\";\n"; OS << " }\n"; OS << "};\n"; diff --git a/gnu/llvm/utils/TableGen/CMakeLists.txt b/gnu/llvm/utils/TableGen/CMakeLists.txt index e8fe30f5ac7..604e3f188ea 100644 --- a/gnu/llvm/utils/TableGen/CMakeLists.txt +++ b/gnu/llvm/utils/TableGen/CMakeLists.txt @@ -22,6 +22,7 @@ add_tablegen(llvm-tblgen LLVM DisassemblerEmitter.cpp FastISelEmitter.cpp FixedLenDecoderEmitter.cpp + GlobalISelEmitter.cpp InstrInfoEmitter.cpp IntrinsicEmitter.cpp OptParserEmitter.cpp @@ -29,7 +30,9 @@ add_tablegen(llvm-tblgen LLVM RegisterInfoEmitter.cpp SearchableTableEmitter.cpp SubtargetEmitter.cpp + SubtargetFeatureInfo.cpp TableGen.cpp + Types.cpp X86DisassemblerTables.cpp X86ModRMFilters.cpp X86RecognizableInstr.cpp diff --git a/gnu/llvm/utils/TableGen/CTagsEmitter.cpp b/gnu/llvm/utils/TableGen/CTagsEmitter.cpp index 35f4ad6dd5b..5213cd90446 100644 --- a/gnu/llvm/utils/TableGen/CTagsEmitter.cpp +++ b/gnu/llvm/utils/TableGen/CTagsEmitter.cpp @@ -37,7 +37,7 @@ public: void emit(raw_ostream &OS) const { const MemoryBuffer *CurMB = SrcMgr.getMemoryBuffer(SrcMgr.FindBufferContainingLoc(Loc)); - const char *BufferName = CurMB->getBufferIdentifier(); + auto BufferName = CurMB->getBufferIdentifier(); std::pair<unsigned, unsigned> LineAndColumn = SrcMgr.getLineAndColumn(Loc); OS << *Id << "\t" << BufferName << "\t" << LineAndColumn.first << "\n"; } diff --git a/gnu/llvm/utils/TableGen/CodeEmitterGen.cpp b/gnu/llvm/utils/TableGen/CodeEmitterGen.cpp index 400913e3274..f34c0ded0a3 100644 --- a/gnu/llvm/utils/TableGen/CodeEmitterGen.cpp +++ b/gnu/llvm/utils/TableGen/CodeEmitterGen.cpp @@ -13,24 +13,35 @@ // //===----------------------------------------------------------------------===// +#include "CodeGenInstruction.h" #include "CodeGenTarget.h" +#include "SubtargetFeatureInfo.h" +#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringExtras.h" -#include "llvm/Support/Debug.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/raw_ostream.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" +#include <cassert> +#include <cstdint> #include <map> +#include <set> #include <string> +#include <utility> #include <vector> + using namespace llvm; namespace { class CodeEmitterGen { RecordKeeper &Records; + public: CodeEmitterGen(RecordKeeper &R) : Records(R) {} void run(raw_ostream &o); + private: int getVariableBit(const std::string &VarName, BitsInit *BI, int bit); std::string getInstructionCase(Record *R, CodeGenTarget &Target); @@ -173,7 +184,6 @@ AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName, } } - std::string CodeEmitterGen::getInstructionCase(Record *R, CodeGenTarget &Target) { std::string Case; @@ -259,7 +269,7 @@ void CodeEmitterGen::run(raw_ostream &o) { o << " UINT64_C(0)\n };\n"; // Map to accumulate all the cases. - std::map<std::string, std::vector<std::string> > CaseMap; + std::map<std::string, std::vector<std::string>> CaseMap; // Construct all cases statement for each opcode for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end(); @@ -269,7 +279,7 @@ void CodeEmitterGen::run(raw_ostream &o) { R->getValueAsBit("isPseudo")) continue; const std::string &InstName = R->getValueAsString("Namespace") + "::" - + R->getName(); + + R->getName().str(); std::string Case = getInstructionCase(R, Target); CaseMap[Case].push_back(InstName); @@ -283,7 +293,7 @@ void CodeEmitterGen::run(raw_ostream &o) { << " switch (opcode) {\n"; // Emit each case statement - std::map<std::string, std::vector<std::string> >::iterator IE, EE; + std::map<std::string, std::vector<std::string>>::iterator IE, EE; for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) { const std::string &Case = IE->first; std::vector<std::string> &InstList = IE->second; @@ -307,9 +317,72 @@ void CodeEmitterGen::run(raw_ostream &o) { << " }\n" << " return Value;\n" << "}\n\n"; + + const auto &All = SubtargetFeatureInfo::getAll(Records); + std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures; + SubtargetFeatures.insert(All.begin(), All.end()); + + o << "#ifdef ENABLE_INSTR_PREDICATE_VERIFIER\n" + << "#undef ENABLE_INSTR_PREDICATE_VERIFIER\n" + << "#include <sstream>\n\n"; + + // Emit the subtarget feature enumeration. + SubtargetFeatureInfo::emitSubtargetFeatureFlagEnumeration(SubtargetFeatures, + o); + + // Emit the name table for error messages. + o << "#ifndef NDEBUG\n"; + SubtargetFeatureInfo::emitNameTable(SubtargetFeatures, o); + o << "#endif // NDEBUG\n"; + + // Emit the available features compute function. + SubtargetFeatureInfo::emitComputeAvailableFeatures( + Target.getName(), "MCCodeEmitter", "computeAvailableFeatures", + SubtargetFeatures, o); + + // Emit the predicate verifier. + o << "void " << Target.getName() + << "MCCodeEmitter::verifyInstructionPredicates(\n" + << " const MCInst &Inst, uint64_t AvailableFeatures) const {\n" + << "#ifndef NDEBUG\n" + << " static uint64_t RequiredFeatures[] = {\n"; + unsigned InstIdx = 0; + for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) { + o << " "; + for (Record *Predicate : Inst->TheDef->getValueAsListOfDefs("Predicates")) { + const auto &I = SubtargetFeatures.find(Predicate); + if (I != SubtargetFeatures.end()) + o << I->second.getEnumName() << " | "; + } + o << "0, // " << Inst->TheDef->getName() << " = " << InstIdx << "\n"; + InstIdx++; + } + o << " };\n\n"; + o << " assert(Inst.getOpcode() < " << InstIdx << ");\n"; + o << " uint64_t MissingFeatures =\n" + << " (AvailableFeatures & RequiredFeatures[Inst.getOpcode()]) ^\n" + << " RequiredFeatures[Inst.getOpcode()];\n" + << " if (MissingFeatures) {\n" + << " std::ostringstream Msg;\n" + << " Msg << \"Attempting to emit \" << " + "MCII.getName(Inst.getOpcode()).str()\n" + << " << \" instruction but the \";\n" + << " for (unsigned i = 0; i < 8 * sizeof(MissingFeatures); ++i)\n" + << " if (MissingFeatures & (1ULL << i))\n" + << " Msg << SubtargetFeatureNames[i] << \" \";\n" + << " Msg << \"predicate(s) are not met\";\n" + << " report_fatal_error(Msg.str());\n" + << " }\n" + << "#else\n" + << "// Silence unused variable warning on targets that don't use MCII for " + "other purposes (e.g. BPF).\n" + << "(void)MCII;\n" + << "#endif // NDEBUG\n"; + o << "}\n"; + o << "#endif\n"; } -} // End anonymous namespace +} // end anonymous namespace namespace llvm { @@ -318,4 +391,4 @@ void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) { CodeEmitterGen(RK).run(OS); } -} // End llvm namespace +} // end namespace llvm diff --git a/gnu/llvm/utils/TableGen/CodeGenDAGPatterns.cpp b/gnu/llvm/utils/TableGen/CodeGenDAGPatterns.cpp index 307a95373c9..b82a76bb035 100644 --- a/gnu/llvm/utils/TableGen/CodeGenDAGPatterns.cpp +++ b/gnu/llvm/utils/TableGen/CodeGenDAGPatterns.cpp @@ -108,24 +108,24 @@ bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP, /// hasIntegerTypes - Return true if this TypeSet contains iAny or an /// integer value type. bool EEVT::TypeSet::hasIntegerTypes() const { - return std::any_of(TypeVec.begin(), TypeVec.end(), isInteger); + return any_of(TypeVec, isInteger); } /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or /// a floating point value type. bool EEVT::TypeSet::hasFloatingPointTypes() const { - return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint); + return any_of(TypeVec, isFloatingPoint); } /// hasScalarTypes - Return true if this TypeSet contains a scalar value type. bool EEVT::TypeSet::hasScalarTypes() const { - return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar); + return any_of(TypeVec, isScalar); } /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector /// value type. bool EEVT::TypeSet::hasVectorTypes() const { - return std::any_of(TypeVec.begin(), TypeVec.end(), isVector); + return any_of(TypeVec, isVector); } @@ -239,8 +239,7 @@ bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) { TypeSet InputSet(*this); // Filter out all the fp types. - TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(), - std::not1(std::ptr_fun(isInteger))), + TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isInteger))), TypeVec.end()); if (TypeVec.empty()) { @@ -265,8 +264,7 @@ bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) { TypeSet InputSet(*this); // Filter out all the integer types. - TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(), - std::not1(std::ptr_fun(isFloatingPoint))), + TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isFloatingPoint))), TypeVec.end()); if (TypeVec.empty()) { @@ -292,8 +290,7 @@ bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) { TypeSet InputSet(*this); // Filter out all the vector types. - TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(), - std::not1(std::ptr_fun(isScalar))), + TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isScalar))), TypeVec.end()); if (TypeVec.empty()) { @@ -317,8 +314,7 @@ bool EEVT::TypeSet::EnforceVector(TreePattern &TP) { bool MadeChange = false; // Filter out all the scalar types. - TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(), - std::not1(std::ptr_fun(isVector))), + TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isVector))), TypeVec.end()); if (TypeVec.empty()) { @@ -395,16 +391,15 @@ bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) { A.getSizeInBits() < B.getSizeInBits()); }); - auto I = std::remove_if(Other.TypeVec.begin(), Other.TypeVec.end(), - [Smallest](MVT OtherVT) { - // Don't compare vector and non-vector types. - if (OtherVT.isVector() != Smallest.isVector()) - return false; - // The getSizeInBits() check here is only needed for vectors, but is - // a subset of the scalar check for scalars so no need to qualify. - return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits()|| - OtherVT.getSizeInBits() < Smallest.getSizeInBits(); - }); + auto I = remove_if(Other.TypeVec, [Smallest](MVT OtherVT) { + // Don't compare vector and non-vector types. + if (OtherVT.isVector() != Smallest.isVector()) + return false; + // The getSizeInBits() check here is only needed for vectors, but is + // a subset of the scalar check for scalars so no need to qualify. + return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() || + OtherVT.getSizeInBits() < Smallest.getSizeInBits(); + }); MadeChange |= I != Other.TypeVec.end(); // If we're about to remove types. Other.TypeVec.erase(I, Other.TypeVec.end()); @@ -428,14 +423,13 @@ bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) { (A.getScalarSizeInBits() == B.getScalarSizeInBits() && A.getSizeInBits() < B.getSizeInBits()); }); - auto I = std::remove_if(TypeVec.begin(), TypeVec.end(), - [Largest](MVT OtherVT) { - // Don't compare vector and non-vector types. - if (OtherVT.isVector() != Largest.isVector()) - return false; - return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() || - OtherVT.getSizeInBits() > Largest.getSizeInBits(); - }); + auto I = remove_if(TypeVec, [Largest](MVT OtherVT) { + // Don't compare vector and non-vector types. + if (OtherVT.isVector() != Largest.isVector()) + return false; + return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() || + OtherVT.getSizeInBits() > Largest.getSizeInBits(); + }); MadeChange |= I != TypeVec.end(); // If we're about to remove types. TypeVec.erase(I, TypeVec.end()); @@ -460,10 +454,9 @@ bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT, TypeSet InputSet(*this); // Filter out all the types which don't have the right element type. - auto I = std::remove_if(TypeVec.begin(), TypeVec.end(), - [VT](MVT VVT) { - return VVT.getVectorElementType().SimpleTy != VT; - }); + auto I = remove_if(TypeVec, [VT](MVT VVT) { + return VVT.getVectorElementType().SimpleTy != VT; + }); MadeChange |= I != TypeVec.end(); TypeVec.erase(I, TypeVec.end()); @@ -547,10 +540,9 @@ bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand, // Only keep types that have less elements than VTOperand. TypeSet InputSet(VTOperand); - auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(), - [NumElems](MVT VVT) { - return VVT.getVectorNumElements() >= NumElems; - }); + auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) { + return VVT.getVectorNumElements() >= NumElems; + }); MadeChange |= I != VTOperand.TypeVec.end(); VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end()); @@ -571,10 +563,9 @@ bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand, // Only keep types that have more elements than 'this'. TypeSet InputSet(*this); - auto I = std::remove_if(TypeVec.begin(), TypeVec.end(), - [NumElems](MVT VVT) { - return VVT.getVectorNumElements() <= NumElems; - }); + auto I = remove_if(TypeVec, [NumElems](MVT VVT) { + return VVT.getVectorNumElements() <= NumElems; + }); MadeChange |= I != TypeVec.end(); TypeVec.erase(I, TypeVec.end()); @@ -609,10 +600,9 @@ bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand, // Only keep types that have same elements as 'this'. TypeSet InputSet(VTOperand); - auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(), - [NumElems](MVT VVT) { - return VVT.getVectorNumElements() != NumElems; - }); + auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) { + return VVT.getVectorNumElements() != NumElems; + }); MadeChange |= I != VTOperand.TypeVec.end(); VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end()); @@ -629,10 +619,9 @@ bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand, // Only keep types that have same elements as VTOperand. TypeSet InputSet(*this); - auto I = std::remove_if(TypeVec.begin(), TypeVec.end(), - [NumElems](MVT VVT) { - return VVT.getVectorNumElements() != NumElems; - }); + auto I = remove_if(TypeVec, [NumElems](MVT VVT) { + return VVT.getVectorNumElements() != NumElems; + }); MadeChange |= I != TypeVec.end(); TypeVec.erase(I, TypeVec.end()); @@ -663,10 +652,8 @@ bool EEVT::TypeSet::EnforceSameSize(EEVT::TypeSet &VTOperand, // Only keep types that have the same size as 'this'. TypeSet InputSet(VTOperand); - auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(), - [&](MVT VT) { - return VT.getSizeInBits() != Size; - }); + auto I = remove_if(VTOperand.TypeVec, + [&](MVT VT) { return VT.getSizeInBits() != Size; }); MadeChange |= I != VTOperand.TypeVec.end(); VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end()); @@ -683,10 +670,8 @@ bool EEVT::TypeSet::EnforceSameSize(EEVT::TypeSet &VTOperand, // Only keep types that have the same size as VTOperand. TypeSet InputSet(*this); - auto I = std::remove_if(TypeVec.begin(), TypeVec.end(), - [&](MVT VT) { - return VT.getSizeInBits() != Size; - }); + auto I = + remove_if(TypeVec, [&](MVT VT) { return VT.getSizeInBits() != Size; }); MadeChange |= I != TypeVec.end(); TypeVec.erase(I, TypeVec.end()); @@ -770,7 +755,7 @@ bool TreePredicateFn::isAlwaysTrue() const { /// Return the name to use in the generated code to reference this, this is /// "Predicate_foo" if from a pattern fragment "foo". std::string TreePredicateFn::getFnName() const { - return "Predicate_" + PatFragRec->getRecord()->getName(); + return "Predicate_" + PatFragRec->getRecord()->getName().str(); } /// getCodeToRunOnSDNode - Return the code for the function body that @@ -820,14 +805,9 @@ static unsigned getPatternSize(const TreePatternNode *P, if (P->isLeaf() && isa<IntInit>(P->getLeafValue())) Size += 2; - // FIXME: This is a hack to statically increase the priority of patterns - // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. - // Later we can allow complexity / cost for each pattern to be (optionally) - // specified. To get best possible pattern match we'll need to dynamically - // calculate the complexity of all patterns a dag can potentially map to. const ComplexPattern *AM = P->getComplexPatternInfo(CGP); if (AM) { - Size += AM->getNumOperands() * 3; + Size += AM->getComplexity(); // We don't want to count any children twice, so return early. return Size; @@ -2026,7 +2006,7 @@ bool TreePatternNode::canPatternMatch(std::string &Reason, // Scan all of the operands of the node and make sure that only the last one // is a constant node, unless the RHS also is. if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) { - bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id. + unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id. for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i) if (OnlyOnRHSOfCommutative(getChild(i))) { Reason="Immediate value must be on the RHS of commutative operators!"; @@ -2092,8 +2072,8 @@ TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){ /// (foo GPR, imm) -> (foo GPR, (imm)) if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) return ParseTreePattern( - DagInit::get(DI, "", - std::vector<std::pair<Init*, std::string> >()), + DagInit::get(DI, nullptr, + std::vector<std::pair<Init*, StringInit*> >()), OpName); // Input argument? @@ -2147,7 +2127,8 @@ TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){ if (Dag->getNumArgs() != 1) error("Type cast only takes one operand!"); - TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0)); + TreePatternNode *New = ParseTreePattern(Dag->getArg(0), + Dag->getArgNameStr(0)); // Apply the type cast. assert(New->getNumTypes() == 1 && "FIXME: Unhandled"); @@ -2198,7 +2179,7 @@ TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){ // Parse all the operands. for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) - Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i))); + Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i))); // If the operator is an intrinsic, then this is just syntactic sugar for for // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and @@ -2246,9 +2227,9 @@ TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){ TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults); Result->setName(OpName); - if (!Dag->getName().empty()) { + if (Dag->getName()) { assert(Result->getName().empty()); - Result->setName(Dag->getName()); + Result->setName(Dag->getNameStr()); } return Result; } @@ -2504,13 +2485,14 @@ void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) { if (!isa<DefInit>(OpsList->getArg(j)) || cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node") P->error("Operands list should all be 'node' values."); - if (OpsList->getArgName(j).empty()) + if (!OpsList->getArgName(j)) P->error("Operands list should have names for each operand!"); - if (!OperandsSet.count(OpsList->getArgName(j))) - P->error("'" + OpsList->getArgName(j) + + StringRef ArgNameStr = OpsList->getArgNameStr(j); + if (!OperandsSet.count(ArgNameStr)) + P->error("'" + ArgNameStr + "' does not occur in pattern or was multiply specified!"); - OperandsSet.erase(OpsList->getArgName(j)); - Args.push_back(OpsList->getArgName(j)); + OperandsSet.erase(ArgNameStr); + Args.push_back(ArgNameStr); } if (!OperandsSet.empty()) @@ -2562,11 +2544,11 @@ void CodeGenDAGPatterns::ParseDefaultOperands() { // Clone the DefaultInfo dag node, changing the operator from 'ops' to // SomeSDnode so that we can parse this. - std::vector<std::pair<Init*, std::string> > Ops; + std::vector<std::pair<Init*, StringInit*> > Ops; for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op) Ops.push_back(std::make_pair(DefaultInfo->getArg(op), DefaultInfo->getArgName(op))); - DagInit *DI = DagInit::get(SomeSDNode, "", Ops); + DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops); // Create a TreePattern to parse this. TreePattern P(DefaultOps[i], DI, false, *this); @@ -3602,10 +3584,9 @@ static void CombineChildVariants(TreePatternNode *Orig, // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a) // which are the same pattern. Ignore the dups. if (R->canPatternMatch(ErrString, CDP) && - std::none_of(OutVariants.begin(), OutVariants.end(), - [&](TreePatternNode *Variant) { - return R->isIsomorphicTo(Variant, DepVars); - })) + none_of(OutVariants, [&](TreePatternNode *Variant) { + return R->isIsomorphicTo(Variant, DepVars); + })) OutVariants.push_back(R.release()); // Increment indices to the next permutation by incrementing the diff --git a/gnu/llvm/utils/TableGen/CodeGenDAGPatterns.h b/gnu/llvm/utils/TableGen/CodeGenDAGPatterns.h index 819c4b8492c..97401cd8171 100644 --- a/gnu/llvm/utils/TableGen/CodeGenDAGPatterns.h +++ b/gnu/llvm/utils/TableGen/CodeGenDAGPatterns.h @@ -412,8 +412,7 @@ public: } void addPredicateFn(const TreePredicateFn &Fn) { assert(!Fn.isAlwaysTrue() && "Empty predicate string!"); - if (std::find(PredicateFns.begin(), PredicateFns.end(), Fn) == - PredicateFns.end()) + if (!is_contained(PredicateFns, Fn)) PredicateFns.push_back(Fn); } @@ -810,11 +809,13 @@ public: LessRecordByID>::const_iterator pf_iterator; pf_iterator pf_begin() const { return PatternFragments.begin(); } pf_iterator pf_end() const { return PatternFragments.end(); } + iterator_range<pf_iterator> ptfs() const { return PatternFragments; } // Patterns to match information. typedef std::vector<PatternToMatch>::const_iterator ptm_iterator; ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); } ptm_iterator ptm_end() const { return PatternsToMatch.end(); } + iterator_range<ptm_iterator> ptms() const { return PatternsToMatch; } /// Parse the Pattern for an instruction, and insert the result in DAGInsts. typedef std::map<Record*, DAGInstruction, LessRecordByID> DAGInstMap; diff --git a/gnu/llvm/utils/TableGen/CodeGenInstruction.cpp b/gnu/llvm/utils/TableGen/CodeGenInstruction.cpp index ec802363030..bb2ec2a64e4 100644 --- a/gnu/llvm/utils/TableGen/CodeGenInstruction.cpp +++ b/gnu/llvm/utils/TableGen/CodeGenInstruction.cpp @@ -53,13 +53,13 @@ CGIOperandList::CGIOperandList(Record *R) : TheDef(R) { OperandList.reserve(e); for (unsigned i = 0; i != e; ++i){ Init *ArgInit; - std::string ArgName; + StringRef ArgName; if (i < NumDefs) { ArgInit = OutDI->getArg(i); - ArgName = OutDI->getArgName(i); + ArgName = OutDI->getArgNameStr(i); } else { ArgInit = InDI->getArg(i-NumDefs); - ArgName = InDI->getArgName(i-NumDefs); + ArgName = InDI->getArgNameStr(i-NumDefs); } DefInit *Arg = dyn_cast<DefInit>(ArgInit); @@ -165,7 +165,7 @@ CGIOperandList::ParseOperandName(const std::string &Op, bool AllowWholeOp) { std::string SubOpName; // Check to see if this is $foo.bar. - std::string::size_type DotIdx = OpName.find_first_of("."); + std::string::size_type DotIdx = OpName.find_first_of('.'); if (DotIdx != std::string::npos) { SubOpName = OpName.substr(DotIdx+1); if (SubOpName.empty()) @@ -193,7 +193,7 @@ CGIOperandList::ParseOperandName(const std::string &Op, bool AllowWholeOp) { // Find the operand with the right name. for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i) - if (MIOpInfo->getArgName(i) == SubOpName) + if (MIOpInfo->getArgNameStr(i) == SubOpName) return std::make_pair(OpIdx, i); // Otherwise, didn't find it! @@ -309,6 +309,7 @@ CodeGenInstruction::CodeGenInstruction(Record *R) isSelect = R->getValueAsBit("isSelect"); isBarrier = R->getValueAsBit("isBarrier"); isCall = R->getValueAsBit("isCall"); + isAdd = R->getValueAsBit("isAdd"); canFoldAsLoad = R->getValueAsBit("canFoldAsLoad"); isPredicable = Operands.isPredicable || R->getValueAsBit("isPredicable"); isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress"); @@ -448,10 +449,10 @@ bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo, if (ADI && ADI->getDef() == InstOpRec) { // If the operand is a record, it must have a name, and the record type // must match up with the instruction's argument type. - if (Result->getArgName(AliasOpNo).empty()) + if (!Result->getArgName(AliasOpNo)) PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) + " must have a name!"); - ResOp = ResultOperand(Result->getArgName(AliasOpNo), ResultRecord); + ResOp = ResultOperand(Result->getArgNameStr(AliasOpNo), ResultRecord); return true; } @@ -469,7 +470,7 @@ bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo, if (!T.getRegisterClass(InstOpRec) .hasSubClass(&T.getRegisterClass(ADI->getDef()))) return false; - ResOp = ResultOperand(Result->getArgName(AliasOpNo), ResultRecord); + ResOp = ResultOperand(Result->getArgNameStr(AliasOpNo), ResultRecord); return true; } @@ -491,7 +492,7 @@ bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo, " is not a member of the " + InstOpRec->getName() + " register class!"); - if (!Result->getArgName(AliasOpNo).empty()) + if (Result->getArgName(AliasOpNo)) PrintFatalError(Loc, "result fixed register argument must " "not have a name!"); @@ -520,7 +521,7 @@ bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo, if (hasSubOps || !InstOpRec->isSubClassOf("Operand")) return false; // Integer arguments can't have names. - if (!Result->getArgName(AliasOpNo).empty()) + if (Result->getArgName(AliasOpNo)) PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) + " must not have a name!"); ResOp = ResultOperand(II->getValue()); @@ -551,7 +552,7 @@ bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo, // MIOperandInfo perhaps? if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type")) return false; - ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef()); + ResOp = ResultOperand(Result->getArgNameStr(AliasOpNo), ADI->getDef()); return true; } @@ -596,14 +597,14 @@ CodeGenInstAlias::CodeGenInstAlias(Record *R, unsigned Variant, StringMap<Record*> NameClass; for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) { DefInit *ADI = dyn_cast<DefInit>(Result->getArg(i)); - if (!ADI || Result->getArgName(i).empty()) + if (!ADI || !Result->getArgName(i)) continue; // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo) // $foo can exist multiple times in the result list, but it must have the // same type. - Record *&Entry = NameClass[Result->getArgName(i)]; + Record *&Entry = NameClass[Result->getArgNameStr(i)]; if (Entry && Entry != ADI->getDef()) - PrintFatalError(R->getLoc(), "result value $" + Result->getArgName(i) + + PrintFatalError(R->getLoc(), "result value $" + Result->getArgNameStr(i) + " is both " + Entry->getName() + " and " + ADI->getDef()->getName() + "!"); Entry = ADI->getDef(); @@ -646,9 +647,9 @@ CodeGenInstAlias::CodeGenInstAlias(Record *R, unsigned Variant, // Take care to instantiate each of the suboperands with the correct // nomenclature: $foo.bar - ResultOperands.emplace_back(Result->getArgName(AliasOpNo) + "." + - MIOI->getArgName(SubOp), - SubRec); + ResultOperands.emplace_back( + Result->getArgName(AliasOpNo)->getAsUnquotedString() + "." + + MIOI->getArgName(SubOp)->getAsUnquotedString(), SubRec); ResultInstOperandIndex.push_back(std::make_pair(i, SubOp)); } ++AliasOpNo; diff --git a/gnu/llvm/utils/TableGen/CodeGenInstruction.h b/gnu/llvm/utils/TableGen/CodeGenInstruction.h index 8e5a03d7b74..75db17b59ac 100644 --- a/gnu/llvm/utils/TableGen/CodeGenInstruction.h +++ b/gnu/llvm/utils/TableGen/CodeGenInstruction.h @@ -230,6 +230,7 @@ template <typename T> class ArrayRef; bool isSelect : 1; bool isBarrier : 1; bool isCall : 1; + bool isAdd : 1; bool canFoldAsLoad : 1; bool mayLoad : 1; bool mayLoad_Unset : 1; diff --git a/gnu/llvm/utils/TableGen/CodeGenIntrinsics.h b/gnu/llvm/utils/TableGen/CodeGenIntrinsics.h index ea3ec67d62e..6df0e6a62ca 100644 --- a/gnu/llvm/utils/TableGen/CodeGenIntrinsics.h +++ b/gnu/llvm/utils/TableGen/CodeGenIntrinsics.h @@ -62,15 +62,23 @@ struct CodeGenIntrinsic { /// accesses that may be performed by the intrinsics. Analogous to /// \c FunctionModRefBehaviour. enum ModRefBits { + /// The intrinsic may access memory that is otherwise inaccessible via + /// LLVM IR. + MR_InaccessibleMem = 1, + + /// The intrinsic may access memory through pointer arguments. + /// LLVM IR. + MR_ArgMem = 2, + /// The intrinsic may access memory anywhere, i.e. it is not restricted /// to access through pointer arguments. - MR_Anywhere = 1, + MR_Anywhere = 4 | MR_ArgMem | MR_InaccessibleMem, /// The intrinsic may read memory. - MR_Ref = 2, + MR_Ref = 8, /// The intrinsic may write memory. - MR_Mod = 4, + MR_Mod = 16, /// The intrinsic may both read and write memory. MR_ModRef = MR_Ref | MR_Mod, @@ -80,11 +88,18 @@ struct CodeGenIntrinsic { /// properties (IntrReadMem, IntrArgMemOnly, etc.). enum ModRefBehavior { NoMem = 0, - ReadArgMem = MR_Ref, + ReadArgMem = MR_Ref | MR_ArgMem, + ReadInaccessibleMem = MR_Ref | MR_InaccessibleMem, + ReadInaccessibleMemOrArgMem = MR_Ref | MR_ArgMem | MR_InaccessibleMem, ReadMem = MR_Ref | MR_Anywhere, - WriteArgMem = MR_Mod, + WriteArgMem = MR_Mod | MR_ArgMem, + WriteInaccessibleMem = MR_Mod | MR_InaccessibleMem, + WriteInaccessibleMemOrArgMem = MR_Mod | MR_ArgMem | MR_InaccessibleMem, WriteMem = MR_Mod | MR_Anywhere, - ReadWriteArgMem = MR_ModRef, + ReadWriteArgMem = MR_ModRef | MR_ArgMem, + ReadWriteInaccessibleMem = MR_ModRef | MR_InaccessibleMem, + ReadWriteInaccessibleMemOrArgMem = MR_ModRef | MR_ArgMem | + MR_InaccessibleMem, ReadWriteMem = MR_ModRef | MR_Anywhere, }; ModRefBehavior ModRef; diff --git a/gnu/llvm/utils/TableGen/CodeGenMapTable.cpp b/gnu/llvm/utils/TableGen/CodeGenMapTable.cpp index 527f530da47..8032d7b3ee9 100644 --- a/gnu/llvm/utils/TableGen/CodeGenMapTable.cpp +++ b/gnu/llvm/utils/TableGen/CodeGenMapTable.cpp @@ -542,6 +542,7 @@ static void emitEnums(raw_ostream &OS, RecordKeeper &Records) { for (unsigned j = i+1; j < FieldValues.size(); j++) { if (CurVal == FieldValues[j]) { FieldValues.erase(FieldValues.begin()+j); + --j; } } } diff --git a/gnu/llvm/utils/TableGen/CodeGenRegisters.cpp b/gnu/llvm/utils/TableGen/CodeGenRegisters.cpp index 626144fbe85..c03e0d1fcf6 100644 --- a/gnu/llvm/utils/TableGen/CodeGenRegisters.cpp +++ b/gnu/llvm/utils/TableGen/CodeGenRegisters.cpp @@ -14,13 +14,33 @@ #include "CodeGenRegisters.h" #include "CodeGenTarget.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/BitVector.h" +#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/IntEqClasses.h" -#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SetVector.h" +#include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/SparseBitVector.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/MathExtras.h" +#include "llvm/Support/raw_ostream.h" #include "llvm/TableGen/Error.h" +#include "llvm/TableGen/Record.h" +#include <algorithm> +#include <cassert> +#include <cstdint> +#include <iterator> +#include <map> +#include <set> +#include <string> +#include <tuple> +#include <utility> +#include <vector> using namespace llvm; @@ -31,7 +51,7 @@ using namespace llvm; //===----------------------------------------------------------------------===// CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum) - : TheDef(R), EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) { + : TheDef(R), EnumValue(Enum), AllSuperRegsCovered(true) { Name = R->getName(); if (R->getValue("Namespace")) Namespace = R->getValueAsString("Namespace"); @@ -42,7 +62,7 @@ CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum) CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace, unsigned Enum) : TheDef(nullptr), Name(N), Namespace(Nspace), Size(-1), Offset(-1), - EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) { + EnumValue(Enum), AllSuperRegsCovered(true) { } std::string CodeGenSubRegIndex::getQualifiedName() const { @@ -82,19 +102,19 @@ void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) { } } -unsigned CodeGenSubRegIndex::computeLaneMask() const { +LaneBitmask CodeGenSubRegIndex::computeLaneMask() const { // Already computed? - if (LaneMask) + if (LaneMask.any()) return LaneMask; // Recursion guard, shouldn't be required. - LaneMask = ~0u; + LaneMask = LaneBitmask::getAll(); // The lane mask is simply the union of all sub-indices. - unsigned M = 0; + LaneBitmask M; for (const auto &C : Composed) M |= C.second->computeLaneMask(); - assert(M && "Missing lane mask, sub-register cycle?"); + assert(M.any() && "Missing lane mask, sub-register cycle?"); LaneMask = M; return LaneMask; } @@ -145,12 +165,13 @@ void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) { } } -const std::string &CodeGenRegister::getName() const { +const StringRef CodeGenRegister::getName() const { assert(TheDef && "no def"); return TheDef->getName(); } namespace { + // Iterate over all register units in a set of registers. class RegUnitIterator { CodeGenRegister::Vec::const_iterator RegI, RegE; @@ -158,7 +179,7 @@ class RegUnitIterator { public: RegUnitIterator(const CodeGenRegister::Vec &Regs): - RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() { + RegI(Regs.begin()), RegE(Regs.end()) { if (RegI != RegE) { UnitI = (*RegI)->getRegUnits().begin(); @@ -190,7 +211,8 @@ protected: } } }; -} // namespace + +} // end anonymous namespace // Return true of this unit appears in RegUnits. static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) { @@ -538,6 +560,7 @@ unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const { // sub-registers. We provide a SetTheory expander class that returns the new // registers. namespace { + struct TupleExpander : SetTheory::Expander { void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override { std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices"); @@ -639,7 +662,8 @@ struct TupleExpander : SetTheory::Expander { } } }; -} + +} // end anonymous namespace //===----------------------------------------------------------------------===// // CodeGenRegisterClass @@ -654,8 +678,7 @@ CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R) : TheDef(R), Name(R->getName()), TopoSigs(RegBank.getNumTopoSigs()), - EnumValue(-1), - LaneMask(0) { + EnumValue(-1) { // Rename anonymous register classes. if (R->getName().size() > 9 && R->getName()[9] == '.') { static unsigned AnonCounter = 0; @@ -767,13 +790,15 @@ bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const { } namespace llvm { + raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) { OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment; for (const auto R : *K.Members) OS << ", " << R->getName(); return OS << " }"; } -} + +} // end namespace llvm // This is a simple lexicographical order that can be used to search for sets. // It is not the same as the topological order provided by TopoOrderRC. @@ -813,7 +838,7 @@ static bool TopoOrderRC(const CodeGenRegisterClass &PA, auto *A = &PA; auto *B = &PB; if (A == B) - return 0; + return false; // Order by ascending spill size. if (A->SpillSize < B->SpillSize) @@ -1167,7 +1192,7 @@ void CodeGenRegBank::computeSubRegLaneMasks() { // First assign individual bits to all the leaf indices. unsigned Bit = 0; // Determine mask of lanes that cover their registers. - CoveringLanes = ~0u; + CoveringLanes = LaneBitmask::getAll(); for (auto &Idx : SubRegIndices) { if (Idx.getComposites().empty()) { if (Bit > 32) { @@ -1175,10 +1200,10 @@ void CodeGenRegBank::computeSubRegLaneMasks() { Twine("Ran out of lanemask bits to represent subregister ") + Idx.getName()); } - Idx.LaneMask = 1u << Bit; + Idx.LaneMask = LaneBitmask(1 << Bit); ++Bit; } else { - Idx.LaneMask = 0; + Idx.LaneMask = LaneBitmask::getNone(); } } @@ -1197,9 +1222,12 @@ void CodeGenRegBank::computeSubRegLaneMasks() { // Moving from a class with no subregisters we just had a single lane: // The subregister must be a leaf subregister and only occupies 1 bit. // Move the bit from the class without subregisters into that position. - unsigned DstBit = Log2_32(Idx.LaneMask); - assert(Idx.LaneMask == 1u << DstBit && "Must be a leaf subregister"); - MaskRolPair MaskRol = { 1, (uint8_t)DstBit }; + static_assert(sizeof(Idx.LaneMask.getAsInteger()) == 4, + "Change Log2_32 to a proper one"); + unsigned DstBit = Log2_32(Idx.LaneMask.getAsInteger()); + assert(Idx.LaneMask == LaneBitmask(1 << DstBit) && + "Must be a leaf subregister"); + MaskRolPair MaskRol = { LaneBitmask(1), (uint8_t)DstBit }; LaneTransforms.push_back(MaskRol); } else { // Go through all leaf subregisters and find the ones that compose with @@ -1213,8 +1241,8 @@ void CodeGenRegBank::computeSubRegLaneMasks() { continue; // Replicate the behaviour from the lane mask generation loop above. unsigned SrcBit = NextBit; - unsigned SrcMask = 1u << SrcBit; - if (NextBit < 31) + LaneBitmask SrcMask = LaneBitmask(1 << SrcBit); + if (NextBit < LaneBitmask::BitWidth-1) ++NextBit; assert(Idx2.LaneMask == SrcMask); @@ -1227,16 +1255,19 @@ void CodeGenRegBank::computeSubRegLaneMasks() { assert(Composite->getComposites().empty()); // Create Mask+Rotate operation and merge with existing ops if possible. - unsigned DstBit = Log2_32(Composite->LaneMask); + static_assert(sizeof(Composite->LaneMask.getAsInteger()) == 4, + "Change Log2_32 to a proper one"); + unsigned DstBit = Log2_32(Composite->LaneMask.getAsInteger()); int Shift = DstBit - SrcBit; - uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift : 32+Shift; + uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift + : LaneBitmask::BitWidth + Shift; for (auto &I : LaneTransforms) { if (I.RotateLeft == RotateLeft) { I.Mask |= SrcMask; - SrcMask = 0; + SrcMask = LaneBitmask::getNone(); } } - if (SrcMask != 0) { + if (SrcMask.any()) { MaskRolPair MaskRol = { SrcMask, RotateLeft }; LaneTransforms.push_back(MaskRol); } @@ -1247,13 +1278,13 @@ void CodeGenRegBank::computeSubRegLaneMasks() { // 0xffffffff (including some irrelevant invalid bits) so that it should // merge with more entries later while compressing the table. if (LaneTransforms.size() == 1) - LaneTransforms[0].Mask = ~0u; + LaneTransforms[0].Mask = LaneBitmask::getAll(); // Further compression optimization: For invalid compositions resulting // in a sequence with 0 entries we can just pick any other. Choose // Mask 0xffffffff with Rotation 0. if (LaneTransforms.size() == 0) { - MaskRolPair P = { ~0u, 0 }; + MaskRolPair P = { LaneBitmask::getAll(), 0 }; LaneTransforms.push_back(P); } } @@ -1263,7 +1294,7 @@ void CodeGenRegBank::computeSubRegLaneMasks() { // Inherit lanes from composites. for (const auto &Idx : SubRegIndices) { - unsigned Mask = Idx.computeLaneMask(); + LaneBitmask Mask = Idx.computeLaneMask(); // If some super-registers without CoveredBySubRegs use this index, we can // no longer assume that the lanes are covering their registers. if (!Idx.AllSuperRegsCovered) @@ -1272,7 +1303,7 @@ void CodeGenRegBank::computeSubRegLaneMasks() { // Compute lane mask combinations for register classes. for (auto &RegClass : RegClasses) { - unsigned LaneMask = 0; + LaneBitmask LaneMask; for (const auto &SubRegIndex : SubRegIndices) { if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr) continue; @@ -1281,14 +1312,15 @@ void CodeGenRegBank::computeSubRegLaneMasks() { // For classes without any subregisters set LaneMask to 1 instead of 0. // This makes it easier for client code to handle classes uniformly. - if (LaneMask == 0) - LaneMask = 1; + if (LaneMask.none()) + LaneMask = LaneBitmask(1); RegClass.LaneMask = LaneMask; } } namespace { + // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is // the transitive closure of the union of overlapping register // classes. Together, the UberRegSets form a partition of the registers. If we @@ -1307,12 +1339,13 @@ namespace { // their weight increased. struct UberRegSet { CodeGenRegister::Vec Regs; - unsigned Weight; + unsigned Weight = 0; CodeGenRegister::RegUnitList SingularDeterminants; - UberRegSet(): Weight(0) {} + UberRegSet() = default; }; -} // namespace + +} // end anonymous namespace // Partition registers into UberRegSets, where each set is the transitive // closure of the union of overlapping register classes. @@ -1321,7 +1354,6 @@ struct UberRegSet { static void computeUberSets(std::vector<UberRegSet> &UberSets, std::vector<UberRegSet*> &RegSets, CodeGenRegBank &RegBank) { - const auto &Registers = RegBank.getRegisters(); // The Register EnumValue is one greater than its index into Registers. @@ -1756,8 +1788,7 @@ void CodeGenRegBank::computeRegUnitSets() { std::vector<unsigned> RUSets; for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) { RegUnitSet &RUSet = RegUnitSets[i]; - if (std::find(RUSet.Units.begin(), RUSet.Units.end(), UnitIdx) - == RUSet.Units.end()) + if (!is_contained(RUSet.Units, UnitIdx)) continue; RUSets.push_back(i); } @@ -1781,7 +1812,8 @@ void CodeGenRegBank::computeRegUnitLaneMasks() { for (auto &Register : Registers) { // Create an initial lane mask for all register units. const auto &RegUnits = Register.getRegUnits(); - CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(RegUnits.count(), 0); + CodeGenRegister::RegUnitLaneMaskList + RegUnitLaneMasks(RegUnits.count(), LaneBitmask::getNone()); // Iterate through SubRegisters. typedef CodeGenRegister::SubRegMap SubRegMap; const SubRegMap &SubRegs = Register.getSubRegs(); @@ -1790,11 +1822,11 @@ void CodeGenRegBank::computeRegUnitLaneMasks() { CodeGenRegister *SubReg = S->second; // Ignore non-leaf subregisters, their lane masks are fully covered by // the leaf subregisters anyway. - if (SubReg->getSubRegs().size() != 0) + if (!SubReg->getSubRegs().empty()) continue; CodeGenSubRegIndex *SubRegIndex = S->first; const CodeGenRegister *SubRegister = S->second; - unsigned LaneMask = SubRegIndex->LaneMask; + LaneBitmask LaneMask = SubRegIndex->LaneMask; // Distribute LaneMask to Register Units touched. for (unsigned SUI : SubRegister->getRegUnits()) { bool Found = false; @@ -2009,7 +2041,6 @@ void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC, } } - // // Infer missing register classes. // diff --git a/gnu/llvm/utils/TableGen/CodeGenRegisters.h b/gnu/llvm/utils/TableGen/CodeGenRegisters.h index b8d47aa4ff8..3ed26fa401a 100644 --- a/gnu/llvm/utils/TableGen/CodeGenRegisters.h +++ b/gnu/llvm/utils/TableGen/CodeGenRegisters.h @@ -18,20 +18,29 @@ #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/BitVector.h" #include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SetVector.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/SparseBitVector.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/StringMap.h" +#include "llvm/ADT/StringRef.h" #include "llvm/CodeGen/MachineValueType.h" +#include "llvm/MC/LaneBitmask.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/SetTheory.h" -#include <cstdlib> +#include <cassert> +#include <cstdint> #include <deque> #include <list> #include <map> #include <string> +#include <utility> #include <vector> namespace llvm { + class CodeGenRegBank; template <typename T, typename Vector, typename Set> class SetVector; @@ -39,8 +48,9 @@ namespace llvm { /// Mask the bits specified in Mask, then rotate them Rol bits to the left /// assuming a wraparound at 32bits. struct MaskRolPair { - unsigned Mask; + LaneBitmask Mask; uint8_t RotateLeft; + bool operator==(const MaskRolPair Other) const { return Mask == Other.Mask && RotateLeft == Other.RotateLeft; } @@ -59,7 +69,7 @@ namespace llvm { uint16_t Size; uint16_t Offset; const unsigned EnumValue; - mutable unsigned LaneMask; + mutable LaneBitmask LaneMask; mutable SmallVector<MaskRolPair,1> CompositionLaneMaskTransform; // Are all super-registers containing this SubRegIndex covered by their @@ -111,7 +121,7 @@ namespace llvm { const CompMap &getComposites() const { return Composed; } // Compute LaneMask from Composed. Return LaneMask. - unsigned computeLaneMask() const; + LaneBitmask computeLaneMask() const; private: CompMap Composed; @@ -136,7 +146,7 @@ namespace llvm { CodeGenRegister(Record *R, unsigned Enum); - const std::string &getName() const; + const StringRef getName() const; // Extract more information from TheDef. This is used to build an object // graph after all CodeGenRegister objects have been created. @@ -197,7 +207,7 @@ namespace llvm { // List of register units in ascending order. typedef SparseBitVector<> RegUnitList; - typedef SmallVector<unsigned, 16> RegUnitLaneMaskList; + typedef SmallVector<LaneBitmask, 16> RegUnitLaneMaskList; // How many entries in RegUnitList are native? RegUnitList NativeRegUnits; @@ -206,7 +216,7 @@ namespace llvm { // This is only valid after computeSubRegs() completes. const RegUnitList &getRegUnits() const { return RegUnits; } - ArrayRef<unsigned> getRegUnitLaneMasks() const { + ArrayRef<LaneBitmask> getRegUnitLaneMasks() const { return makeArrayRef(RegUnitLaneMasks).slice(0, NativeRegUnits.count()); } @@ -266,7 +276,7 @@ namespace llvm { class CodeGenRegisterClass { CodeGenRegister::Vec Members; // Allocation orders. Order[0] always contains all registers in Members. - std::vector<SmallVector<Record*, 16> > Orders; + std::vector<SmallVector<Record*, 16>> Orders; // Bit mask of sub-classes including this, indexed by their EnumValue. BitVector SubClasses; // List of super-classes, topologocally ordered to have the larger classes @@ -307,7 +317,7 @@ namespace llvm { std::string AltOrderSelect; uint8_t AllocationPriority; /// Contains the combination of the lane masks of all subregisters. - unsigned LaneMask; + LaneBitmask LaneMask; /// True if there are at least 2 subregisters which do not interfere. bool HasDisjunctSubRegs; bool CoveredBySubRegs; @@ -463,10 +473,10 @@ namespace llvm { std::string Name; std::vector<unsigned> Units; - unsigned Weight; // Cache the sum of all unit weights. - unsigned Order; // Cache the sort key. + unsigned Weight = 0; // Cache the sum of all unit weights. + unsigned Order = 0; // Cache the sort key. - RegUnitSet() : Weight(0), Order(0) {} + RegUnitSet() = default; }; // Base vector for identifying TopoSigs. The contents uniquely identify a @@ -515,7 +525,7 @@ namespace llvm { // NOTE: This could grow beyond the number of register classes when we map // register units to lists of unit sets. If the list of unit sets does not // already exist for a register class, we create a new entry in this vector. - std::vector<std::vector<unsigned> > RegClassUnitSets; + std::vector<std::vector<unsigned>> RegClassUnitSets; // Give each register unit set an order based on sorting criteria. std::vector<unsigned> RegUnitSetOrder; @@ -532,6 +542,7 @@ namespace llvm { void computeInferredRegisterClasses(); void inferCommonSubClass(CodeGenRegisterClass *RC); void inferSubClassWithSubReg(CodeGenRegisterClass *RC); + void inferMatchingSuperRegClass(CodeGenRegisterClass *RC) { inferMatchingSuperRegClass(RC, RegClasses.begin()); } @@ -590,6 +601,7 @@ namespace llvm { } const std::deque<CodeGenRegister> &getRegisters() { return Registers; } + const StringMap<CodeGenRegister*> &getRegistersByName() { return RegistersByName; } @@ -674,6 +686,7 @@ namespace llvm { unsigned getRegSetIDAt(unsigned Order) const { return RegUnitSetOrder[Order]; } + const RegUnitSet &getRegSetAt(unsigned Order) const { return RegUnitSets[RegUnitSetOrder[Order]]; } @@ -721,8 +734,9 @@ namespace llvm { // Bit mask of lanes that cover their registers. A sub-register index whose // LaneMask is contained in CoveringLanes will be completely covered by // another sub-register with the same or larger lane mask. - unsigned CoveringLanes; + LaneBitmask CoveringLanes; }; -} -#endif +} // end namespace llvm + +#endif // LLVM_UTILS_TABLEGEN_CODEGENREGISTERS_H diff --git a/gnu/llvm/utils/TableGen/CodeGenSchedule.cpp b/gnu/llvm/utils/TableGen/CodeGenSchedule.cpp index d1b141e3160..cae1cf4b861 100644 --- a/gnu/llvm/utils/TableGen/CodeGenSchedule.cpp +++ b/gnu/llvm/utils/TableGen/CodeGenSchedule.cpp @@ -12,12 +12,21 @@ // //===----------------------------------------------------------------------===// +#include "CodeGenInstruction.h" #include "CodeGenSchedule.h" #include "CodeGenTarget.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallSet.h" +#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/Support/Casting.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/raw_ostream.h" #include "llvm/Support/Regex.h" #include "llvm/TableGen/Error.h" +#include <algorithm> +#include <iterator> +#include <utility> using namespace llvm; @@ -31,6 +40,7 @@ static void dumpIdxVec(ArrayRef<unsigned> V) { #endif namespace { + // (instrs a, b, ...) Evaluate and union all arguments. Identical to AddOp. struct InstrsOp : public SetTheory::Operator { void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts, @@ -76,6 +86,7 @@ struct InstRegexOp : public SetTheory::Operator { } } }; + } // end anonymous namespace /// CodeGenModels ctor interprets machine model records and populates maps. @@ -356,8 +367,7 @@ bool CodeGenSchedModels::hasReadOfWrite(Record *WriteDef) const { continue; RecVec ValidWrites = ReadDef->getValueAsListOfDefs("ValidWrites"); - if (std::find(ValidWrites.begin(), ValidWrites.end(), WriteDef) - != ValidWrites.end()) { + if (is_contained(ValidWrites, WriteDef)) { return true; } } @@ -365,6 +375,7 @@ bool CodeGenSchedModels::hasReadOfWrite(Record *WriteDef) const { } namespace llvm { + void splitSchedReadWrites(const RecVec &RWDefs, RecVec &WriteDefs, RecVec &ReadDefs) { for (RecIter RWI = RWDefs.begin(), RWE = RWDefs.end(); RWI != RWE; ++RWI) { @@ -376,7 +387,8 @@ void splitSchedReadWrites(const RecVec &RWDefs, } } } -} // namespace llvm + +} // end namespace llvm // Split the SchedReadWrites defs and call findRWs for each list. void CodeGenSchedModels::findRWs(const RecVec &RWDefs, @@ -574,11 +586,14 @@ void CodeGenSchedModels::collectSchedClasses() { dbgs() << " " << SchedReads[*RI].Name; dbgs() << '\n'; } - for (std::vector<CodeGenProcModel>::iterator PI = ProcModels.begin(), - PE = ProcModels.end(); PI != PE; ++PI) { - if (!std::count(ProcIndices.begin(), ProcIndices.end(), PI->Index)) - dbgs() << "No machine model for " << Inst->TheDef->getName() - << " on processor " << PI->ModelName << '\n'; + // If ProcIndices contains zero, the class applies to all processors. + if (!std::count(ProcIndices.begin(), ProcIndices.end(), 0)) { + for (std::vector<CodeGenProcModel>::iterator PI = ProcModels.begin(), + PE = ProcModels.end(); PI != PE; ++PI) { + if (!std::count(ProcIndices.begin(), ProcIndices.end(), PI->Index)) + dbgs() << "No machine model for " << Inst->TheDef->getName() + << " on processor " << PI->ModelName << '\n'; + } } } } @@ -674,7 +689,7 @@ void CodeGenSchedModels::createInstRWClass(Record *InstRWDef) { // intersects with an existing class via a previous InstRWDef. Instrs that do // not intersect with an existing class refer back to their former class as // determined from ItinDef or SchedRW. - SmallVector<std::pair<unsigned, SmallVector<Record *, 8> >, 4> ClassInstrs; + SmallVector<std::pair<unsigned, SmallVector<Record *, 8>>, 4> ClassInstrs; // Sort Instrs into sets. const RecVec *InstDefs = Sets.expand(InstRWDef); if (InstDefs->empty()) @@ -913,6 +928,7 @@ void CodeGenSchedModels::inferFromInstRWs(unsigned SCIdx) { } namespace { + // Helper for substituteVariantOperand. struct TransVariant { Record *VarOrSeqDef; // Variant or sequence. @@ -969,7 +985,8 @@ private: std::vector<TransVariant> &IntersectingVariants); void pushVariant(const TransVariant &VInfo, bool IsRead); }; -} // anonymous + +} // end anonymous namespace // Return true if this predicate is mutually exclusive with a PredTerm. This // degenerates into checking if the predicate is mutually exclusive with any @@ -982,7 +999,6 @@ private: // conditions implicitly negate any prior condition. bool PredTransitions::mutuallyExclusive(Record *PredDef, ArrayRef<PredCheck> Term) { - for (ArrayRef<PredCheck>::iterator I = Term.begin(), E = Term.end(); I != E; ++I) { if (I->Predicate == PredDef) @@ -1029,7 +1045,7 @@ static bool hasVariant(ArrayRef<PredTransition> Transitions, for (ArrayRef<PredTransition>::iterator PTI = Transitions.begin(), PTE = Transitions.end(); PTI != PTE; ++PTI) { - for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator + for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator WSI = PTI->WriteSequences.begin(), WSE = PTI->WriteSequences.end(); WSI != WSE; ++WSI) { for (SmallVectorImpl<unsigned>::const_iterator @@ -1038,7 +1054,7 @@ static bool hasVariant(ArrayRef<PredTransition> Transitions, return true; } } - for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator + for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator RSI = PTI->ReadSequences.begin(), RSE = PTI->ReadSequences.end(); RSI != RSE; ++RSI) { for (SmallVectorImpl<unsigned>::const_iterator @@ -1145,7 +1161,6 @@ void PredTransitions::getIntersectingVariants( // specified by VInfo. void PredTransitions:: pushVariant(const TransVariant &VInfo, bool IsRead) { - PredTransition &Trans = TransVec[VInfo.TransVecIdx]; // If this operand transition is reached through a processor-specific alias, @@ -1168,7 +1183,7 @@ pushVariant(const TransVariant &VInfo, bool IsRead) { const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(VInfo.RWIdx, IsRead); - SmallVectorImpl<SmallVector<unsigned,4> > &RWSequences = IsRead + SmallVectorImpl<SmallVector<unsigned,4>> &RWSequences = IsRead ? Trans.ReadSequences : Trans.WriteSequences; if (SchedRW.IsVariadic) { unsigned OperIdx = RWSequences.size()-1; @@ -1264,7 +1279,7 @@ void PredTransitions::substituteVariants(const PredTransition &Trans) { TransVec.back().ProcIndices = Trans.ProcIndices; // Visit each original write sequence. - for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator + for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator WSI = Trans.WriteSequences.begin(), WSE = Trans.WriteSequences.end(); WSI != WSE; ++WSI) { // Push a new (empty) write sequence onto all partial Transitions. @@ -1275,7 +1290,7 @@ void PredTransitions::substituteVariants(const PredTransition &Trans) { substituteVariantOperand(*WSI, /*IsRead=*/false, StartIdx); } // Visit each original read sequence. - for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator + for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator RSI = Trans.ReadSequences.begin(), RSE = Trans.ReadSequences.end(); RSI != RSE; ++RSI) { // Push a new (empty) read sequence onto all partial Transitions. @@ -1296,7 +1311,7 @@ static void inferFromTransitions(ArrayRef<PredTransition> LastTransitions, for (ArrayRef<PredTransition>::iterator I = LastTransitions.begin(), E = LastTransitions.end(); I != E; ++I) { IdxVec OperWritesVariant; - for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator + for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator WSI = I->WriteSequences.begin(), WSE = I->WriteSequences.end(); WSI != WSE; ++WSI) { // Create a new write representing the expanded sequence. @@ -1304,7 +1319,7 @@ static void inferFromTransitions(ArrayRef<PredTransition> LastTransitions, SchedModels.findOrInsertRW(*WSI, /*IsRead=*/false)); } IdxVec OperReadsVariant; - for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator + for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator RSI = I->ReadSequences.begin(), RSE = I->ReadSequences.end(); RSI != RSE; ++RSI) { // Create a new read representing the expanded sequence. @@ -1400,8 +1415,7 @@ bool CodeGenSchedModels::hasSuperGroup(RecVec &SubUnits, CodeGenProcModel &PM) { PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources"); RecIter RI = SubUnits.begin(), RE = SubUnits.end(); for ( ; RI != RE; ++RI) { - if (std::find(SuperUnits.begin(), SuperUnits.end(), *RI) - == SuperUnits.end()) { + if (!is_contained(SuperUnits, *RI)) { break; } } @@ -1500,9 +1514,7 @@ void CodeGenSchedModels::collectProcResources() { if (!(*RI)->getValueInit("SchedModel")->isComplete()) continue; CodeGenProcModel &PM = getProcModel((*RI)->getValueAsDef("SchedModel")); - RecIter I = std::find(PM.ProcResourceDefs.begin(), - PM.ProcResourceDefs.end(), *RI); - if (I == PM.ProcResourceDefs.end()) + if (!is_contained(PM.ProcResourceDefs, *RI)) PM.ProcResourceDefs.push_back(*RI); } // Finalize each ProcModel by sorting the record arrays. @@ -1568,15 +1580,14 @@ void CodeGenSchedModels::checkCompleteness() { const CodeGenSchedClass &SC = getSchedClass(SCIdx); if (!SC.Writes.empty()) continue; - if (SC.ItinClassDef != nullptr) + if (SC.ItinClassDef != nullptr && + SC.ItinClassDef->getName() != "NoItinerary") continue; const RecVec &InstRWs = SC.InstRWs; - auto I = std::find_if(InstRWs.begin(), InstRWs.end(), - [&ProcModel] (const Record *R) { - return R->getValueAsDef("SchedModel") == - ProcModel.ModelDef; - }); + auto I = find_if(InstRWs, [&ProcModel](const Record *R) { + return R->getValueAsDef("SchedModel") == ProcModel.ModelDef; + }); if (I == InstRWs.end()) { PrintError("'" + ProcModel.ModelName + "' lacks information for '" + Inst->TheDef->getName() + "'"); @@ -1660,7 +1671,6 @@ void CodeGenSchedModels::collectRWResources(unsigned RWIdx, bool IsRead, void CodeGenSchedModels::collectRWResources(ArrayRef<unsigned> Writes, ArrayRef<unsigned> Reads, ArrayRef<unsigned> ProcIndices) { - for (unsigned Idx : Writes) collectRWResources(Idx, /*IsRead=*/false, ProcIndices); @@ -1668,7 +1678,6 @@ void CodeGenSchedModels::collectRWResources(ArrayRef<unsigned> Writes, collectRWResources(Idx, /*IsRead=*/true, ProcIndices); } - // Find the processor's resource units for this kind of resource. Record *CodeGenSchedModels::findProcResUnits(Record *ProcResKind, const CodeGenProcModel &PM) const { @@ -1716,13 +1725,11 @@ Record *CodeGenSchedModels::findProcResUnits(Record *ProcResKind, // Iteratively add a resource and its super resources. void CodeGenSchedModels::addProcResource(Record *ProcResKind, CodeGenProcModel &PM) { - for (;;) { + while (true) { Record *ProcResUnits = findProcResUnits(ProcResKind, PM); // See if this ProcResource is already associated with this processor. - RecIter I = std::find(PM.ProcResourceDefs.begin(), - PM.ProcResourceDefs.end(), ProcResUnits); - if (I != PM.ProcResourceDefs.end()) + if (is_contained(PM.ProcResourceDefs, ProcResUnits)) return; PM.ProcResourceDefs.push_back(ProcResUnits); @@ -1741,8 +1748,7 @@ void CodeGenSchedModels::addWriteRes(Record *ProcWriteResDef, unsigned PIdx) { assert(PIdx && "don't add resources to an invalid Processor model"); RecVec &WRDefs = ProcModels[PIdx].WriteResDefs; - RecIter WRI = std::find(WRDefs.begin(), WRDefs.end(), ProcWriteResDef); - if (WRI != WRDefs.end()) + if (is_contained(WRDefs, ProcWriteResDef)) return; WRDefs.push_back(ProcWriteResDef); @@ -1758,15 +1764,13 @@ void CodeGenSchedModels::addWriteRes(Record *ProcWriteResDef, unsigned PIdx) { void CodeGenSchedModels::addReadAdvance(Record *ProcReadAdvanceDef, unsigned PIdx) { RecVec &RADefs = ProcModels[PIdx].ReadAdvanceDefs; - RecIter I = std::find(RADefs.begin(), RADefs.end(), ProcReadAdvanceDef); - if (I != RADefs.end()) + if (is_contained(RADefs, ProcReadAdvanceDef)) return; RADefs.push_back(ProcReadAdvanceDef); } unsigned CodeGenProcModel::getProcResourceIdx(Record *PRDef) const { - RecIter PRPos = std::find(ProcResourceDefs.begin(), ProcResourceDefs.end(), - PRDef); + RecIter PRPos = find(ProcResourceDefs, PRDef); if (PRPos == ProcResourceDefs.end()) PrintFatalError(PRDef->getLoc(), "ProcResource def is not included in " "the ProcResources list for " + ModelName); @@ -1842,7 +1846,7 @@ void PredTransitions::dump() const { << ":" << PCI->Predicate->getName(); } dbgs() << "},\n => {"; - for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator + for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator WSI = TI->WriteSequences.begin(), WSE = TI->WriteSequences.end(); WSI != WSE; ++WSI) { dbgs() << "("; diff --git a/gnu/llvm/utils/TableGen/CodeGenTarget.cpp b/gnu/llvm/utils/TableGen/CodeGenTarget.cpp index 245b9eeeed8..6503d5af2d4 100644 --- a/gnu/llvm/utils/TableGen/CodeGenTarget.cpp +++ b/gnu/llvm/utils/TableGen/CodeGenTarget.cpp @@ -138,7 +138,7 @@ std::string llvm::getQualifiedName(const Record *R) { if (R->getValue("Namespace")) Namespace = R->getValueAsString("Namespace"); if (Namespace.empty()) return R->getName(); - return Namespace + "::" + R->getName(); + return Namespace + "::" + R->getName().str(); } @@ -157,7 +157,7 @@ CodeGenTarget::CodeGenTarget(RecordKeeper &records) CodeGenTarget::~CodeGenTarget() { } -const std::string &CodeGenTarget::getName() const { +const StringRef CodeGenTarget::getName() const { return TargetRec->getName(); } @@ -301,7 +301,7 @@ GetInstByName(const char *Name, /// their enum value. void CodeGenTarget::ComputeInstrsByEnum() const { static const char *const FixedInstrs[] = { -#define HANDLE_TARGET_OPCODE(OPC, NUM) #OPC, +#define HANDLE_TARGET_OPCODE(OPC) #OPC, #include "llvm/Target/TargetOpcodes.def" nullptr}; const auto &Insts = getInstructions(); @@ -393,6 +393,16 @@ ComplexPattern::ComplexPattern(Record *R) { SelectFunc = R->getValueAsString("SelectFunc"); RootNodes = R->getValueAsListOfDefs("RootNodes"); + // FIXME: This is a hack to statically increase the priority of patterns which + // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best + // possible pattern match we'll need to dynamically calculate the complexity + // of all patterns a dag can potentially map to. + int64_t RawComplexity = R->getValueAsInt("Complexity"); + if (RawComplexity == -1) + Complexity = NumOperands * 3; + else + Complexity = RawComplexity; + // Parse the properties. Properties = 0; std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties"); @@ -550,8 +560,7 @@ CodeGenIntrinsic::CodeGenIntrinsic(Record *R) { // overloaded, all the types can be specified directly. assert(((!TyEl->isSubClassOf("LLVMExtendedType") && !TyEl->isSubClassOf("LLVMTruncatedType") && - !TyEl->isSubClassOf("LLVMVectorSameWidth") && - !TyEl->isSubClassOf("LLVMPointerToElt")) || + !TyEl->isSubClassOf("LLVMVectorSameWidth")) || VT == MVT::iAny || VT == MVT::vAny) && "Expected iAny or vAny type"); } else @@ -584,7 +593,12 @@ CodeGenIntrinsic::CodeGenIntrinsic(Record *R) { else if (Property->getName() == "IntrWriteMem") ModRef = ModRefBehavior(ModRef & ~MR_Ref); else if (Property->getName() == "IntrArgMemOnly") - ModRef = ModRefBehavior(ModRef & ~MR_Anywhere); + ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem); + else if (Property->getName() == "IntrInaccessibleMemOnly") + ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_InaccessibleMem); + else if (Property->getName() == "IntrInaccessibleMemOrArgMemOnly") + ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem | + MR_InaccessibleMem); else if (Property->getName() == "Commutative") isCommutative = true; else if (Property->getName() == "Throws") diff --git a/gnu/llvm/utils/TableGen/CodeGenTarget.h b/gnu/llvm/utils/TableGen/CodeGenTarget.h index 85a8c1b1887..c822e940ffa 100644 --- a/gnu/llvm/utils/TableGen/CodeGenTarget.h +++ b/gnu/llvm/utils/TableGen/CodeGenTarget.h @@ -82,7 +82,7 @@ public: ~CodeGenTarget(); Record *getTargetRecord() const { return TargetRec; } - const std::string &getName() const; + const StringRef getName() const; /// getInstNamespace - Return the target-specific instruction namespace. /// @@ -139,7 +139,7 @@ public: /// supported by the target (i.e. there are registers that directly hold it). bool isLegalValueType(MVT::SimpleValueType VT) const { ArrayRef<MVT::SimpleValueType> LegalVTs = getLegalValueTypes(); - return std::find(LegalVTs.begin(), LegalVTs.end(), VT) != LegalVTs.end(); + return is_contained(LegalVTs, VT); } CodeGenSchedModels &getSchedModels() const; @@ -196,8 +196,8 @@ class ComplexPattern { std::string SelectFunc; std::vector<Record*> RootNodes; unsigned Properties; // Node properties + unsigned Complexity; public: - ComplexPattern() : NumOperands(0) {} ComplexPattern(Record *R); MVT::SimpleValueType getValueType() const { return Ty; } @@ -207,6 +207,7 @@ public: return RootNodes; } bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); } + unsigned getComplexity() const { return Complexity; } }; } // End llvm namespace diff --git a/gnu/llvm/utils/TableGen/DAGISelEmitter.cpp b/gnu/llvm/utils/TableGen/DAGISelEmitter.cpp index 0fe3bbd8d78..60fe866f194 100644 --- a/gnu/llvm/utils/TableGen/DAGISelEmitter.cpp +++ b/gnu/llvm/utils/TableGen/DAGISelEmitter.cpp @@ -121,7 +121,7 @@ struct PatternSortingPredicate { void DAGISelEmitter::run(raw_ostream &OS) { emitSourceFileHeader("DAG Instruction Selector for the " + - CGP.getTargetInfo().getName() + " target", OS); + CGP.getTargetInfo().getName().str() + " target", OS); OS << "// *** NOTE: This file is #included into the middle of the target\n" << "// *** instruction selector class. These functions are really " diff --git a/gnu/llvm/utils/TableGen/DAGISelMatcherGen.cpp b/gnu/llvm/utils/TableGen/DAGISelMatcherGen.cpp index 4110e9725b5..aafc1157893 100644 --- a/gnu/llvm/utils/TableGen/DAGISelMatcherGen.cpp +++ b/gnu/llvm/utils/TableGen/DAGISelMatcherGen.cpp @@ -250,7 +250,7 @@ void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) { // If we have a physreg reference like (mul gpr:$src, EAX) then we need to // record the register if (LeafRec->isSubClassOf("Register")) { - AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(), + AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName().str(), NextRecordedOperandNo)); PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++)); return; @@ -354,7 +354,7 @@ void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N, unsigned OpNo = 0; if (N->NodeHasProperty(SDNPHasChain, CGP)) { // Record the node and remember it in our chained nodes list. - AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() + + AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() + "' chained node", NextRecordedOperandNo)); // Remember all of the input chains our pattern will match. @@ -418,7 +418,7 @@ void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N, // TODO: This redundantly records nodes with both glues and chains. // Record the node and remember it in our chained nodes list. - AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() + + AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() + "' glue output node", NextRecordedOperandNo)); } @@ -887,7 +887,7 @@ EmitResultInstructionAsOperand(const TreePatternNode *N, assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) && "Node has no result"); - AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(), + AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName().str(), ResultVTs, InstOps, NodeHasChain, TreeHasInGlue, TreeHasOutGlue, NodeHasMemRefs, NumFixedArityOperands, diff --git a/gnu/llvm/utils/TableGen/DAGISelMatcherOpt.cpp b/gnu/llvm/utils/TableGen/DAGISelMatcherOpt.cpp index ad385fac043..783b35e745f 100644 --- a/gnu/llvm/utils/TableGen/DAGISelMatcherOpt.cpp +++ b/gnu/llvm/utils/TableGen/DAGISelMatcherOpt.cpp @@ -200,8 +200,15 @@ static void FactorNodes(std::unique_ptr<Matcher> &MatcherPtr) { std::unique_ptr<Matcher> Child(Scope->takeChild(i)); FactorNodes(Child); - if (Matcher *N = Child.release()) - OptionsToMatch.push_back(N); + if (Child) { + // If the child is a ScopeMatcher we can just merge its contents. + if (auto *SM = dyn_cast<ScopeMatcher>(Child.get())) { + for (unsigned j = 0, e = SM->getNumChildren(); j != e; ++j) + OptionsToMatch.push_back(SM->takeChild(j)); + } else { + OptionsToMatch.push_back(Child.release()); + } + } } SmallVector<Matcher*, 32> NewOptionsToMatch; @@ -414,9 +421,7 @@ static void FactorNodes(std::unique_ptr<Matcher> &MatcherPtr) { } Matcher *Entries[2] = { PrevMatcher, MatcherWithoutCTM }; - std::unique_ptr<Matcher> Case(new ScopeMatcher(Entries)); - FactorNodes(Case); - Cases[Entry-1].second = Case.release(); + Cases[Entry-1].second = new ScopeMatcher(Entries); continue; } @@ -424,6 +429,16 @@ static void FactorNodes(std::unique_ptr<Matcher> &MatcherPtr) { Cases.push_back(std::make_pair(CTMTy, MatcherWithoutCTM)); } + // Make sure we recursively factor any scopes we may have created. + for (auto &M : Cases) { + if (ScopeMatcher *SM = dyn_cast<ScopeMatcher>(M.second)) { + std::unique_ptr<Matcher> Scope(SM); + FactorNodes(Scope); + M.second = Scope.release(); + assert(M.second && "null matcher"); + } + } + if (Cases.size() != 1) { MatcherPtr.reset(new SwitchTypeMatcher(Cases)); } else { diff --git a/gnu/llvm/utils/TableGen/DFAPacketizerEmitter.cpp b/gnu/llvm/utils/TableGen/DFAPacketizerEmitter.cpp index e31caaf3c98..f879a5bae21 100644 --- a/gnu/llvm/utils/TableGen/DFAPacketizerEmitter.cpp +++ b/gnu/llvm/utils/TableGen/DFAPacketizerEmitter.cpp @@ -19,14 +19,18 @@ #include "CodeGenTarget.h" #include "llvm/ADT/DenseSet.h" -#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/raw_ostream.h" +#include <cassert> +#include <cstdint> #include <map> +#include <set> #include <string> -#include <queue> +#include <vector> using namespace llvm; @@ -58,6 +62,7 @@ typedef int64_t DFAStateInput; #define DFA_TBLTYPE "int64_t" // For generating DFAStateInputTable. namespace { + DFAInput addDFAFuncUnits(DFAInput Inp, unsigned FuncUnits) { return (Inp << DFA_MAX_RESOURCES) | FuncUnits; } @@ -67,12 +72,13 @@ namespace { /// DFAPacketizerEmitter.cpp. DFAInput getDFAInsnInput(const std::vector<unsigned> &InsnClass) { DFAInput InsnInput = 0; - assert ((InsnClass.size() <= DFA_MAX_RESTERMS) && - "Exceeded maximum number of DFA terms"); + assert((InsnClass.size() <= DFA_MAX_RESTERMS) && + "Exceeded maximum number of DFA terms"); for (auto U : InsnClass) InsnInput = addDFAFuncUnits(InsnInput, U); return InsnInput; } + } // end anonymous namespace // -------------------------------------------------------------------- @@ -98,6 +104,7 @@ void dbgsIndent(unsigned indent); // for resource tracking. // namespace { + class DFAPacketizerEmitter { private: std::string TargetName; @@ -150,10 +157,8 @@ public: void run(raw_ostream &OS); }; -} // end anonymous namespace // -// // State represents the usage of machine resources if the packet contains // a set of instruction classes. // @@ -174,7 +179,6 @@ public: // A State instance also contains a collection of transitions from that state: // a map from inputs to new states. // -namespace { class State { public: static int currentStateNum; @@ -204,6 +208,7 @@ class State { // bool canMaybeAddInsnClass(std::vector<unsigned> &InsnClass, std::map<unsigned, unsigned> &ComboBitToBitsMap) const; + // // AddInsnClass - Return all combinations of resource reservation // which are possible from this state (PossibleStates). @@ -214,6 +219,7 @@ class State { void AddInsnClass(std::vector<unsigned> &InsnClass, std::map<unsigned, unsigned> &ComboBitToBitsMap, std::set<unsigned> &PossibleStates) const; + // // AddInsnClassStages - Return all combinations of resource reservation // resulting from the cross product of all stages for this InsnClass @@ -225,31 +231,31 @@ class State { unsigned prevState, unsigned origState, DenseSet<unsigned> &VisitedResourceStates, std::set<unsigned> &PossibleStates) const; + // // addTransition - Add a transition from this state given the input InsnClass // void addTransition(std::vector<unsigned> InsnClass, const State *To) const; + // // hasTransition - Returns true if there is a transition from this state // given the input InsnClass // bool hasTransition(std::vector<unsigned> InsnClass) const; }; -} // end anonymous namespace // // class DFA: deterministic finite automaton for processor resource tracking. // -namespace { class DFA { public: - DFA(); + DFA() = default; // Set of states. Need to keep this sorted to emit the transition table. typedef std::set<State> StateSet; StateSet states; - State *currentState; + State *currentState = nullptr; // // Modify the DFA. @@ -263,6 +269,7 @@ public: int numInsnClasses = 0, int maxResources = 0, int numCombos = 0, int maxStages = 0); }; + } // end anonymous namespace #ifndef NDEBUG @@ -314,8 +321,6 @@ void dbgsIndent(unsigned indent) { State::State() : stateNum(currentStateNum++), isInitial(false) {} -DFA::DFA(): currentState(nullptr) {} - // // addTransition - Add a transition from this state given the input InsnClass // @@ -370,7 +375,6 @@ void State::AddInsnClassStages(std::vector<unsigned> &InsnClass, unsigned prevState, unsigned origState, DenseSet<unsigned> &VisitedResourceStates, std::set<unsigned> &PossibleStates) const { - assert((chkstage < numstages) && "AddInsnClassStages: stage out of range"); unsigned thisStage = InsnClass[chkstage]; @@ -469,7 +473,6 @@ bool State::canMaybeAddInsnClass(std::vector<unsigned> &InsnClass, std::map<unsigned, unsigned> &ComboBitToBitsMap) const { for (std::set<unsigned>::const_iterator SI = stateInfo.begin(); SI != stateInfo.end(); ++SI) { - // Check to see if all required resources are available. bool available = true; @@ -514,8 +517,7 @@ const State &DFA::newState() { int State::currentStateNum = 0; DFAPacketizerEmitter::DFAPacketizerEmitter(RecordKeeper &R): - TargetName(CodeGenTarget(R).getName()), - allInsnClasses(), Records(R) {} + TargetName(CodeGenTarget(R).getName()), Records(R) {} // // writeTableAndAPI - Print out a table representing the DFA and the @@ -531,7 +533,6 @@ DFAPacketizerEmitter::DFAPacketizerEmitter(RecordKeeper &R): void DFA::writeTableAndAPI(raw_ostream &OS, const std::string &TargetName, int numInsnClasses, int maxResources, int numCombos, int maxStages) { - unsigned numStates = states.size(); DEBUG(dbgs() << "-----------------------------------------------------------------------------\n"); @@ -783,7 +784,7 @@ int DFAPacketizerEmitter::collectOneInsnClass(const std::string &ProcName, DEBUG(dbgs() << " (bits: 0x" << utohexstr(UnitBitValue) << ")\n"); } - if (UnitBits.size() > 0) + if (!UnitBits.empty()) allInsnClasses.push_back(UnitBits); DEBUG({ @@ -831,7 +832,6 @@ int DFAPacketizerEmitter::collectAllInsnClasses(const std::string &ProcName, // Run the worklist algorithm to generate the DFA. // void DFAPacketizerEmitter::run(raw_ostream &OS) { - // Collect processor iteraries. std::vector<Record*> ProcItinList = Records.getAllDerivedDefinitions("ProcessorItineraries"); @@ -890,7 +890,6 @@ void DFAPacketizerEmitter::run(raw_ostream &OS) { Initial->isInitial = true; Initial->stateInfo.insert(0x0); SmallVector<const State*, 32> WorkList; -// std::queue<State*> WorkList; std::map<std::set<unsigned>, const State*> Visited; WorkList.push_back(Initial); @@ -937,7 +936,7 @@ void DFAPacketizerEmitter::run(raw_ostream &OS) { current->canMaybeAddInsnClass(InsnClass, ComboBitToBitsMap)) { const State *NewState = nullptr; current->AddInsnClass(InsnClass, ComboBitToBitsMap, NewStateResources); - if (NewStateResources.size() == 0) { + if (NewStateResources.empty()) { DEBUG(dbgs() << " Skipped - no new states generated\n"); continue; } @@ -989,4 +988,4 @@ void EmitDFAPacketizer(RecordKeeper &RK, raw_ostream &OS) { DFAPacketizerEmitter(RK).run(OS); } -} // end namespaec llvm +} // end namespace llvm diff --git a/gnu/llvm/utils/TableGen/DisassemblerEmitter.cpp b/gnu/llvm/utils/TableGen/DisassemblerEmitter.cpp index 44815b05f27..6e1d8dde981 100644 --- a/gnu/llvm/utils/TableGen/DisassemblerEmitter.cpp +++ b/gnu/llvm/utils/TableGen/DisassemblerEmitter.cpp @@ -104,7 +104,7 @@ extern void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS, void EmitDisassembler(RecordKeeper &Records, raw_ostream &OS) { CodeGenTarget Target(Records); - emitSourceFileHeader(" * " + Target.getName() + " Disassembler", OS); + emitSourceFileHeader(" * " + Target.getName().str() + " Disassembler", OS); // X86 uses a custom disassembler. if (Target.getName() == "X86") { diff --git a/gnu/llvm/utils/TableGen/FastISelEmitter.cpp b/gnu/llvm/utils/TableGen/FastISelEmitter.cpp index debb12c4f51..43c6a982633 100644 --- a/gnu/llvm/utils/TableGen/FastISelEmitter.cpp +++ b/gnu/llvm/utils/TableGen/FastISelEmitter.cpp @@ -564,8 +564,7 @@ void FastISelMap::collectPatterns(CodeGenDAGPatterns &CGP) { Operands.PrintManglingSuffix(SuffixOS, ImmediatePredicates, true); SuffixOS.flush(); if (!StringSwitch<bool>(ManglingSuffix) - .Cases("", "r", "rr", "ri", "rf", true) - .Cases("rri", "i", "f", true) + .Cases("", "r", "rr", "ri", "i", "f", true) .Default(false)) continue; @@ -874,7 +873,7 @@ void EmitFastISel(RecordKeeper &RK, raw_ostream &OS) { CodeGenDAGPatterns CGP(RK); const CodeGenTarget &Target = CGP.getTargetInfo(); emitSourceFileHeader("\"Fast\" Instruction Selector for the " + - Target.getName() + " target", OS); + Target.getName().str() + " target", OS); // Determine the target's namespace name. std::string InstNS = Target.getInstNamespace() + "::"; diff --git a/gnu/llvm/utils/TableGen/FixedLenDecoderEmitter.cpp b/gnu/llvm/utils/TableGen/FixedLenDecoderEmitter.cpp index 0506400b90f..e1aaeccb08d 100644 --- a/gnu/llvm/utils/TableGen/FixedLenDecoderEmitter.cpp +++ b/gnu/llvm/utils/TableGen/FixedLenDecoderEmitter.cpp @@ -12,21 +12,32 @@ // //===----------------------------------------------------------------------===// +#include "CodeGenInstruction.h" #include "CodeGenTarget.h" #include "llvm/ADT/APInt.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/CachedHashString.h" #include "llvm/ADT/SmallString.h" +#include "llvm/ADT/SetVector.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" -#include "llvm/ADT/Twine.h" #include "llvm/MC/MCFixedLenDisassembler.h" -#include "llvm/Support/DataTypes.h" +#include "llvm/Support/Casting.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/raw_ostream.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" +#include <algorithm> +#include <cassert> +#include <cstddef> +#include <cstdint> #include <map> +#include <memory> +#include <set> #include <string> #include <utility> #include <vector> @@ -36,6 +47,7 @@ using namespace llvm; #define DEBUG_TYPE "decoder-emitter" namespace { + struct EncodingField { unsigned Base, Width, Offset; EncodingField(unsigned B, unsigned W, unsigned O) @@ -66,8 +78,8 @@ typedef std::vector<uint8_t> DecoderTable; typedef uint32_t DecoderFixup; typedef std::vector<DecoderFixup> FixupList; typedef std::vector<FixupList> FixupScopeList; -typedef SmallSetVector<std::string, 16> PredicateSet; -typedef SmallSetVector<std::string, 16> DecoderSet; +typedef SmallSetVector<CachedHashString, 16> PredicateSet; +typedef SmallSetVector<CachedHashString, 16> DecoderSet; struct DecoderTableInfo { DecoderTable Table; FixupScopeList FixupStack; @@ -75,13 +87,10 @@ struct DecoderTableInfo { DecoderSet Decoders; }; -} // End anonymous namespace - -namespace { class FixedLenDecoderEmitter { ArrayRef<const CodeGenInstruction *> NumberedInstructions; -public: +public: // Defaults preserved here for documentation, even though they aren't // strictly necessary given the way that this is currently being called. FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace, @@ -111,13 +120,15 @@ public: private: CodeGenTarget Target; + public: std::string PredicateNamespace; std::string GuardPrefix, GuardPostfix; std::string ReturnOK, ReturnFail; std::string Locals; }; -} // End anonymous namespace + +} // end anonymous namespace // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system // for a bit value. @@ -134,12 +145,15 @@ typedef enum { static bool ValueSet(bit_value_t V) { return (V == BIT_TRUE || V == BIT_FALSE); } + static bool ValueNotSet(bit_value_t V) { return (V == BIT_UNSET); } + static int Value(bit_value_t V) { return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1); } + static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) { if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index))) return bit->getValue() ? BIT_TRUE : BIT_FALSE; @@ -147,6 +161,7 @@ static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) { // The bit is uninitialized. return BIT_UNSET; } + // Prints the bit value for each position. static void dumpBits(raw_ostream &o, const BitsInit &bits) { for (unsigned index = bits.getNumBits(); index > 0; --index) { @@ -166,19 +181,18 @@ static void dumpBits(raw_ostream &o, const BitsInit &bits) { } } -static BitsInit &getBitsField(const Record &def, const char *str) { +static BitsInit &getBitsField(const Record &def, StringRef str) { BitsInit *bits = def.getValueAsBitsInit(str); return *bits; } -// Forward declaration. -namespace { -class FilterChooser; -} // End anonymous namespace - // Representation of the instruction to work on. typedef std::vector<bit_value_t> insn_t; +namespace { + +class FilterChooser; + /// Filter - Filter works with FilterChooser to produce the decoding tree for /// the ISA. /// @@ -215,7 +229,6 @@ typedef std::vector<bit_value_t> insn_t; /// decoder could try to decode the even/odd register numbering and assign to /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a" /// version and return the Opcode since the two have the same Asm format string. -namespace { class Filter { protected: const FilterChooser *Owner;// points to the FilterChooser who owns this filter @@ -224,7 +237,7 @@ protected: bool Mixed; // a mixed region contains both set and unset bits // Map of well-known segment value to the set of uid's with that value. - std::map<uint64_t, std::vector<unsigned> > FilteredInstructions; + std::map<uint64_t, std::vector<unsigned>> FilteredInstructions; // Set of uid's with non-constant segment values. std::vector<unsigned> VariableInstructions; @@ -239,11 +252,18 @@ protected: unsigned LastOpcFiltered; public: + Filter(Filter &&f); + Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed); + + ~Filter() = default; + unsigned getNumFiltered() const { return NumFiltered; } + unsigned getSingletonOpc() const { assert(NumFiltered == 1); return LastOpcFiltered; } + // Return the filter chooser for the group of instructions without constant // segment values. const FilterChooser &getVariableFC() const { @@ -252,11 +272,6 @@ public: return *(FilterChooserMap.find((unsigned)-1)->second); } - Filter(Filter &&f); - Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed); - - ~Filter(); - // Divides the decoding task into sub tasks and delegates them to the // inferior FilterChooser's. // @@ -272,8 +287,9 @@ public: // Returns the number of fanout produced by the filter. More fanout implies // the filter distinguishes more categories of instructions. unsigned usefulness() const; -}; // End of class Filter -} // End anonymous namespace +}; // end class Filter + +} // end anonymous namespace // These are states of our finite state machines used in FilterChooser's // filterProcessor() which produces the filter candidates to use. @@ -301,6 +317,7 @@ typedef enum { /// decoding tree. And each case is delegated to an inferior FilterChooser to /// decide what further remaining bits to look at. namespace { + class FilterChooser { protected: friend class Filter; @@ -312,7 +329,7 @@ protected: const std::vector<unsigned> &Opcodes; // Lookup table for the operand decoding of instructions. - const std::map<unsigned, std::vector<OperandInfo> > &Operands; + const std::map<unsigned, std::vector<OperandInfo>> &Operands; // Vector of candidate filters. std::vector<Filter> Filters; @@ -333,16 +350,13 @@ protected: // Parent emitter const FixedLenDecoderEmitter *Emitter; - FilterChooser(const FilterChooser &) = delete; - void operator=(const FilterChooser &) = delete; public: - FilterChooser(ArrayRef<const CodeGenInstruction *> Insts, const std::vector<unsigned> &IDs, - const std::map<unsigned, std::vector<OperandInfo> > &Ops, + const std::map<unsigned, std::vector<OperandInfo>> &Ops, unsigned BW, const FixedLenDecoderEmitter *E) - : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(), + : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1), BitWidth(BW), Emitter(E) { doFilter(); @@ -350,16 +364,18 @@ public: FilterChooser(ArrayRef<const CodeGenInstruction *> Insts, const std::vector<unsigned> &IDs, - const std::map<unsigned, std::vector<OperandInfo> > &Ops, + const std::map<unsigned, std::vector<OperandInfo>> &Ops, const std::vector<bit_value_t> &ParentFilterBitValues, const FilterChooser &parent) : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), - Filters(), FilterBitValues(ParentFilterBitValues), - Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth), - Emitter(parent.Emitter) { + FilterBitValues(ParentFilterBitValues), Parent(&parent), BestIndex(-1), + BitWidth(parent.BitWidth), Emitter(parent.Emitter) { doFilter(); } + FilterChooser(const FilterChooser &) = delete; + void operator=(const FilterChooser &) = delete; + unsigned getBitWidth() const { return BitWidth; } protected: @@ -384,7 +400,7 @@ protected: } // Returns the record name. - const std::string &nameWithID(unsigned Opcode) const { + const StringRef nameWithID(unsigned Opcode) const { return AllInstructions[Opcode]->TheDef->getName(); } @@ -476,7 +492,8 @@ public: // instructions. void emitTableEntries(DecoderTableInfo &TableInfo) const; }; -} // End anonymous namespace + +} // end anonymous namespace /////////////////////////// // // @@ -527,9 +544,6 @@ Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, && "Filter returns no instruction categories"); } -Filter::~Filter() { -} - // Divides the decoding task into sub tasks and delegates them to the // inferior FilterChooser's. // @@ -1071,7 +1085,7 @@ void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation, for (const auto &Op : Operands.find(Opc)->second) { // If a custom instruction decoder was specified, use that. - if (Op.numFields() == 0 && Op.Decoder.size()) { + if (Op.numFields() == 0 && !Op.Decoder.empty()) { HasCompleteDecoder = Op.HasCompleteDecoder; OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder << "(MI, insn, Address, Decoder)" @@ -1106,11 +1120,9 @@ unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders, // overkill for now, though. // Make sure the predicate is in the table. - Decoders.insert(StringRef(Decoder)); + Decoders.insert(CachedHashString(Decoder)); // Now figure out the index for when we write out the table. - DecoderSet::const_iterator P = std::find(Decoders.begin(), - Decoders.end(), - Decoder.str()); + DecoderSet::const_iterator P = find(Decoders, Decoder.str()); return (unsigned)(P - Decoders.begin()); } @@ -1143,7 +1155,7 @@ bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation, StringRef SR(P); std::pair<StringRef, StringRef> pairs = SR.split(','); - while (pairs.second.size()) { + while (!pairs.second.empty()) { emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace); o << " && "; pairs = pairs.second.split(','); @@ -1181,11 +1193,9 @@ unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo, // overkill for now, though. // Make sure the predicate is in the table. - TableInfo.Predicates.insert(Predicate.str()); + TableInfo.Predicates.insert(CachedHashString(Predicate)); // Now figure out the index for when we write out the table. - PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(), - TableInfo.Predicates.end(), - Predicate.str()); + PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate); return (unsigned)(P - TableInfo.Predicates.begin()); } @@ -1374,7 +1384,6 @@ void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo, Best.getVariableFC().emitTableEntries(TableInfo); } - // Assign a single filter and run with it. Top level API client can initialize // with a single filter to start the filtering process. void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit, @@ -1692,9 +1701,37 @@ void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const { } } +static std::string findOperandDecoderMethod(TypedInit *TI) { + std::string Decoder; + + RecordRecTy *Type = cast<RecordRecTy>(TI->getType()); + Record *TypeRecord = Type->getRecord(); + + RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod"); + StringInit *String = DecoderString ? + dyn_cast<StringInit>(DecoderString->getValue()) : nullptr; + if (String) { + Decoder = String->getValue(); + if (!Decoder.empty()) + return Decoder; + } + + if (TypeRecord->isSubClassOf("RegisterOperand")) + TypeRecord = TypeRecord->getValueAsDef("RegClass"); + + if (TypeRecord->isSubClassOf("RegisterClass")) { + Decoder = "Decode" + TypeRecord->getName().str() + "RegisterClass"; + } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) { + Decoder = "DecodePointerLikeRegClass" + + utostr(TypeRecord->getValueAsInt("RegClassKind")); + } + + return Decoder; +} + static bool populateInstruction(CodeGenTarget &Target, const CodeGenInstruction &CGI, unsigned Opc, - std::map<unsigned, std::vector<OperandInfo> > &Operands){ + std::map<unsigned, std::vector<OperandInfo>> &Operands){ const Record &Def = *CGI.TheDef; // If all the bit positions are not specified; do not decode this instruction. // We are bound to fail! For proper disassembly, the well-known encoding bits @@ -1722,13 +1759,15 @@ static bool populateInstruction(CodeGenTarget &Target, // Gather the outputs/inputs of the instruction, so we can find their // positions in the encoding. This assumes for now that they appear in the // MCInst in the order that they're listed. - std::vector<std::pair<Init*, std::string> > InOutOperands; + std::vector<std::pair<Init*, StringRef>> InOutOperands; DagInit *Out = Def.getValueAsDag("OutOperandList"); DagInit *In = Def.getValueAsDag("InOperandList"); for (unsigned i = 0; i < Out->getNumArgs(); ++i) - InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i))); + InOutOperands.push_back(std::make_pair(Out->getArg(i), + Out->getArgNameStr(i))); for (unsigned i = 0; i < In->getNumArgs(); ++i) - InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i))); + InOutOperands.push_back(std::make_pair(In->getArg(i), + In->getArgNameStr(i))); // Search for tied operands, so that we can correctly instantiate // operands that are not explicitly represented in the encoding. @@ -1743,7 +1782,7 @@ static bool populateInstruction(CodeGenTarget &Target, } } - std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands; + std::map<std::string, std::vector<OperandInfo>> NumberedInsnOperands; std::set<std::string> NumberedInsnOperandsNoTie; if (Target.getInstructionSet()-> getValueAsBit("decodePositionallyEncodedOperands")) { @@ -1828,7 +1867,7 @@ static bool populateInstruction(CodeGenTarget &Target, Name << "(" << SO.first << ", " << SO.second << ") => " << Vals[i].getName() << "\n"); - std::string Decoder = ""; + std::string Decoder; Record *TypeRecord = CGI.Operands[SO.first].Rec; RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod"); @@ -1852,7 +1891,7 @@ static bool populateInstruction(CodeGenTarget &Target, if (TypeRecord->isSubClassOf("RegisterOperand")) TypeRecord = TypeRecord->getValueAsDef("RegClass"); if (TypeRecord->isSubClassOf("RegisterClass")) { - Decoder = "Decode" + TypeRecord->getName() + "RegisterClass"; + Decoder = "Decode" + TypeRecord->getName().str() + "RegisterClass"; isReg = true; } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) { Decoder = "DecodePointerLikeRegClass" + @@ -1917,33 +1956,13 @@ static bool populateInstruction(CodeGenTarget &Target, continue; } - std::string Decoder = ""; - - // At this point, we can locate the field, but we need to know how to - // interpret it. As a first step, require the target to provide callbacks - // for decoding register classes. - // FIXME: This need to be extended to handle instructions with custom - // decoder methods, and operands with (simple) MIOperandInfo's. TypedInit *TI = cast<TypedInit>(Op.first); - RecordRecTy *Type = cast<RecordRecTy>(TI->getType()); - Record *TypeRecord = Type->getRecord(); - bool isReg = false; - if (TypeRecord->isSubClassOf("RegisterOperand")) - TypeRecord = TypeRecord->getValueAsDef("RegClass"); - if (TypeRecord->isSubClassOf("RegisterClass")) { - Decoder = "Decode" + TypeRecord->getName() + "RegisterClass"; - isReg = true; - } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) { - Decoder = "DecodePointerLikeRegClass" + - utostr(TypeRecord->getValueAsInt("RegClassKind")); - isReg = true; - } - RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod"); - StringInit *String = DecoderString ? - dyn_cast<StringInit>(DecoderString->getValue()) : nullptr; - if (!isReg && String && String->getValue() != "") - Decoder = String->getValue(); + // At this point, we can locate the decoder field, but we need to know how + // to interpret it. As a first step, require the target to provide + // callbacks for decoding register classes. + std::string Decoder = findOperandDecoderMethod(TI); + Record *TypeRecord = cast<RecordRecTy>(TI->getType())->getRecord(); RecordVal *HasCompleteDecoderVal = TypeRecord->getValue("hasCompleteDecoder"); @@ -2009,7 +2028,6 @@ static bool populateInstruction(CodeGenTarget &Target, Operands[Opc] = InsnOperands; - #if 0 DEBUG({ // Dumps the instruction encoding bits. @@ -2062,7 +2080,7 @@ static void emitDecodeInstruction(formatted_raw_ostream &OS) { << " const uint8_t *Ptr = DecodeTable;\n" << " uint32_t CurFieldValue = 0;\n" << " DecodeStatus S = MCDisassembler::Success;\n" - << " for (;;) {\n" + << " while (true) {\n" << " ptrdiff_t Loc = Ptr - DecodeTable;\n" << " switch (*Ptr) {\n" << " default:\n" @@ -2230,8 +2248,8 @@ void FixedLenDecoderEmitter::run(raw_ostream &o) { // Parameterize the decoders based on namespace and instruction width. NumberedInstructions = Target.getInstructionsByEnumValue(); std::map<std::pair<std::string, unsigned>, - std::vector<unsigned> > OpcMap; - std::map<unsigned, std::vector<OperandInfo> > Operands; + std::vector<unsigned>> OpcMap; + std::map<unsigned, std::vector<OperandInfo>> Operands; for (unsigned i = 0; i < NumberedInstructions.size(); ++i) { const CodeGenInstruction *Inst = NumberedInstructions[i]; @@ -2304,4 +2322,4 @@ void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS, ROK, RFail, L).run(OS); } -} // End llvm namespace +} // end namespace llvm diff --git a/gnu/llvm/utils/TableGen/GlobalISelEmitter.cpp b/gnu/llvm/utils/TableGen/GlobalISelEmitter.cpp new file mode 100644 index 00000000000..2bc6181045c --- /dev/null +++ b/gnu/llvm/utils/TableGen/GlobalISelEmitter.cpp @@ -0,0 +1,388 @@ +//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +/// \file +/// This tablegen backend emits code for use by the GlobalISel instruction +/// selector. See include/llvm/CodeGen/TargetGlobalISel.td. +/// +/// This file analyzes the patterns recognized by the SelectionDAGISel tablegen +/// backend, filters out the ones that are unsupported, maps +/// SelectionDAG-specific constructs to their GlobalISel counterpart +/// (when applicable: MVT to LLT; SDNode to generic Instruction). +/// +/// Not all patterns are supported: pass the tablegen invocation +/// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped, +/// as well as why. +/// +/// The generated file defines a single method: +/// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const; +/// intended to be used in InstructionSelector::select as the first-step +/// selector for the patterns that don't require complex C++. +/// +/// FIXME: We'll probably want to eventually define a base +/// "TargetGenInstructionSelector" class. +/// +//===----------------------------------------------------------------------===// + +#include "CodeGenDAGPatterns.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/Statistic.h" +#include "llvm/CodeGen/MachineValueType.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/TableGen/Error.h" +#include "llvm/TableGen/Record.h" +#include "llvm/TableGen/TableGenBackend.h" +#include <string> +using namespace llvm; + +#define DEBUG_TYPE "gisel-emitter" + +STATISTIC(NumPatternTotal, "Total number of patterns"); +STATISTIC(NumPatternSkipped, "Number of patterns skipped"); +STATISTIC(NumPatternEmitted, "Number of patterns emitted"); + +static cl::opt<bool> WarnOnSkippedPatterns( + "warn-on-skipped-patterns", + cl::desc("Explain why a pattern was skipped for inclusion " + "in the GlobalISel selector"), + cl::init(false)); + +namespace { + +class GlobalISelEmitter { +public: + explicit GlobalISelEmitter(RecordKeeper &RK); + void run(raw_ostream &OS); + +private: + const RecordKeeper &RK; + const CodeGenDAGPatterns CGP; + const CodeGenTarget &Target; + + /// Keep track of the equivalence between SDNodes and Instruction. + /// This is defined using 'GINodeEquiv' in the target description. + DenseMap<Record *, const CodeGenInstruction *> NodeEquivs; + + void gatherNodeEquivs(); + const CodeGenInstruction *findNodeEquiv(Record *N); + + struct SkipReason { + std::string Reason; + }; + + /// Analyze pattern \p P, possibly emitting matching code for it to \p OS. + /// Otherwise, return a reason why this pattern was skipped for emission. + Optional<SkipReason> runOnPattern(const PatternToMatch &P, + raw_ostream &OS); +}; + +} // end anonymous namespace + +//===- Helper functions ---------------------------------------------------===// + +/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for +/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...). +static Optional<std::string> MVTToLLT(MVT::SimpleValueType SVT) { + std::string TyStr; + raw_string_ostream OS(TyStr); + MVT VT(SVT); + if (VT.isVector() && VT.getVectorNumElements() != 1) { + OS << "LLT::vector(" << VT.getVectorNumElements() << ", " + << VT.getScalarSizeInBits() << ")"; + } else if (VT.isInteger() || VT.isFloatingPoint()) { + OS << "LLT::scalar(" << VT.getSizeInBits() << ")"; + } else { + return None; + } + OS.flush(); + return TyStr; +} + +static bool isTrivialOperatorNode(const TreePatternNode *N) { + return !N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn(); +} + +//===- Matchers -----------------------------------------------------------===// + +struct Matcher { + virtual ~Matcher() {} + virtual void emit(raw_ostream &OS) const = 0; +}; + +raw_ostream &operator<<(raw_ostream &S, const Matcher &M) { + M.emit(S); + return S; +} + +struct MatchAction { + virtual ~MatchAction() {} + virtual void emit(raw_ostream &OS) const = 0; +}; + +raw_ostream &operator<<(raw_ostream &S, const MatchAction &A) { + A.emit(S); + return S; +} + +struct MatchOpcode : public Matcher { + MatchOpcode(const CodeGenInstruction *I) : I(I) {} + const CodeGenInstruction *I; + + virtual void emit(raw_ostream &OS) const { + OS << "I.getOpcode() == " << I->Namespace << "::" << I->TheDef->getName(); + } +}; + +struct MatchRegOpType : public Matcher { + MatchRegOpType(unsigned OpIdx, std::string Ty) + : OpIdx(OpIdx), Ty(Ty) {} + unsigned OpIdx; + std::string Ty; + + virtual void emit(raw_ostream &OS) const { + OS << "MRI.getType(I.getOperand(" << OpIdx << ").getReg()) == (" << Ty + << ")"; + } +}; + +struct MatchRegOpBank : public Matcher { + MatchRegOpBank(unsigned OpIdx, const CodeGenRegisterClass &RC) + : OpIdx(OpIdx), RC(RC) {} + unsigned OpIdx; + const CodeGenRegisterClass &RC; + + virtual void emit(raw_ostream &OS) const { + OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName() + << "RegClass) == RBI.getRegBank(I.getOperand(" << OpIdx + << ").getReg(), MRI, TRI))"; + } +}; + +struct MatchMBBOp : public Matcher { + MatchMBBOp(unsigned OpIdx) : OpIdx(OpIdx) {} + unsigned OpIdx; + + virtual void emit(raw_ostream &OS) const { + OS << "I.getOperand(" << OpIdx << ").isMBB()"; + } +}; + +struct MutateOpcode : public MatchAction { + MutateOpcode(const CodeGenInstruction *I) : I(I) {} + const CodeGenInstruction *I; + + virtual void emit(raw_ostream &OS) const { + OS << "I.setDesc(TII.get(" << I->Namespace << "::" << I->TheDef->getName() + << "));"; + } +}; + +class MatcherEmitter { + const PatternToMatch &P; + +public: + std::vector<std::unique_ptr<Matcher>> Matchers; + std::vector<std::unique_ptr<MatchAction>> Actions; + + MatcherEmitter(const PatternToMatch &P) : P(P) {} + + void emit(raw_ostream &OS) { + if (Matchers.empty()) + llvm_unreachable("Unexpected empty matcher!"); + + OS << " // Src: " << *P.getSrcPattern() << "\n" + << " // Dst: " << *P.getDstPattern() << "\n"; + + OS << " if ((" << *Matchers.front() << ")"; + for (auto &MA : makeArrayRef(Matchers).drop_front()) + OS << " &&\n (" << *MA << ")"; + OS << ") {\n"; + + for (auto &MA : Actions) + OS << " " << *MA << "\n"; + + OS << " constrainSelectedInstRegOperands(I, TII, TRI, RBI);\n"; + OS << " return true;\n"; + OS << " }\n"; + } +}; + +//===- GlobalISelEmitter class --------------------------------------------===// + +void GlobalISelEmitter::gatherNodeEquivs() { + assert(NodeEquivs.empty()); + for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv")) + NodeEquivs[Equiv->getValueAsDef("Node")] = + &Target.getInstruction(Equiv->getValueAsDef("I")); +} + +const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) { + return NodeEquivs.lookup(N); +} + +GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK) + : RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {} + +//===- Emitter ------------------------------------------------------------===// + +Optional<GlobalISelEmitter::SkipReason> +GlobalISelEmitter::runOnPattern(const PatternToMatch &P, raw_ostream &OS) { + + // Keep track of the matchers and actions to emit. + MatcherEmitter M(P); + + // First, analyze the whole pattern. + // If the entire pattern has a predicate (e.g., target features), ignore it. + if (!P.getPredicates()->getValues().empty()) + return SkipReason{"Pattern has a predicate"}; + + // Physreg imp-defs require additional logic. Ignore the pattern. + if (!P.getDstRegs().empty()) + return SkipReason{"Pattern defines a physical register"}; + + // Next, analyze the pattern operators. + TreePatternNode *Src = P.getSrcPattern(); + TreePatternNode *Dst = P.getDstPattern(); + + // If the root of either pattern isn't a simple operator, ignore it. + if (!isTrivialOperatorNode(Dst)) + return SkipReason{"Dst pattern root isn't a trivial operator"}; + if (!isTrivialOperatorNode(Src)) + return SkipReason{"Src pattern root isn't a trivial operator"}; + + Record *DstOp = Dst->getOperator(); + if (!DstOp->isSubClassOf("Instruction")) + return SkipReason{"Pattern operator isn't an instruction"}; + + auto &DstI = Target.getInstruction(DstOp); + + auto SrcGIOrNull = findNodeEquiv(Src->getOperator()); + if (!SrcGIOrNull) + return SkipReason{"Pattern operator lacks an equivalent Instruction"}; + auto &SrcGI = *SrcGIOrNull; + + // The operators look good: match the opcode and mutate it to the new one. + M.Matchers.emplace_back(new MatchOpcode(&SrcGI)); + M.Actions.emplace_back(new MutateOpcode(&DstI)); + + // Next, analyze the children, only accepting patterns that don't require + // any change to operands. + if (Src->getNumChildren() != Dst->getNumChildren()) + return SkipReason{"Src/dst patterns have a different # of children"}; + + unsigned OpIdx = 0; + + // Start with the defined operands (i.e., the results of the root operator). + if (DstI.Operands.NumDefs != Src->getExtTypes().size()) + return SkipReason{"Src pattern results and dst MI defs are different"}; + + for (const EEVT::TypeSet &Ty : Src->getExtTypes()) { + Record *DstIOpRec = DstI.Operands[OpIdx].Rec; + if (!DstIOpRec->isSubClassOf("RegisterClass")) + return SkipReason{"Dst MI def isn't a register class"}; + + auto OpTyOrNone = MVTToLLT(Ty.getConcrete()); + if (!OpTyOrNone) + return SkipReason{"Dst operand has an unsupported type"}; + + M.Matchers.emplace_back(new MatchRegOpType(OpIdx, *OpTyOrNone)); + M.Matchers.emplace_back( + new MatchRegOpBank(OpIdx, Target.getRegisterClass(DstIOpRec))); + ++OpIdx; + } + + // Finally match the used operands (i.e., the children of the root operator). + for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) { + auto *SrcChild = Src->getChild(i); + auto *DstChild = Dst->getChild(i); + + // Patterns can reorder operands. Ignore those for now. + if (SrcChild->getName() != DstChild->getName()) + return SkipReason{"Src/dst pattern children not in same order"}; + + // The only non-leaf child we accept is 'bb': it's an operator because + // BasicBlockSDNode isn't inline, but in MI it's just another operand. + if (!SrcChild->isLeaf()) { + if (DstChild->isLeaf() || + SrcChild->getOperator() != DstChild->getOperator()) + return SkipReason{"Src/dst pattern child operator mismatch"}; + + if (SrcChild->getOperator()->isSubClassOf("SDNode")) { + auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator()); + if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { + M.Matchers.emplace_back(new MatchMBBOp(OpIdx++)); + continue; + } + } + return SkipReason{"Src pattern child isn't a leaf node"}; + } + + if (SrcChild->getLeafValue() != DstChild->getLeafValue()) + return SkipReason{"Src/dst pattern child leaf mismatch"}; + + // Otherwise, we're looking for a bog-standard RegisterClass operand. + if (SrcChild->hasAnyPredicate()) + return SkipReason{"Src pattern child has predicate"}; + auto *ChildRec = cast<DefInit>(SrcChild->getLeafValue())->getDef(); + if (!ChildRec->isSubClassOf("RegisterClass")) + return SkipReason{"Src pattern child isn't a RegisterClass"}; + + ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes(); + if (ChildTypes.size() != 1) + return SkipReason{"Src pattern child has multiple results"}; + + auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete()); + if (!OpTyOrNone) + return SkipReason{"Src operand has an unsupported type"}; + + M.Matchers.emplace_back(new MatchRegOpType(OpIdx, *OpTyOrNone)); + M.Matchers.emplace_back( + new MatchRegOpBank(OpIdx, Target.getRegisterClass(ChildRec))); + ++OpIdx; + } + + // We're done with this pattern! Emit the processed result. + M.emit(OS); + ++NumPatternEmitted; + return None; +} + +void GlobalISelEmitter::run(raw_ostream &OS) { + // Track the GINodeEquiv definitions. + gatherNodeEquivs(); + + emitSourceFileHeader(("Global Instruction Selector for the " + + Target.getName() + " target").str(), OS); + OS << "bool " << Target.getName() + << "InstructionSelector::selectImpl" + "(MachineInstr &I) const {\n const MachineRegisterInfo &MRI = " + "I.getParent()->getParent()->getRegInfo();\n"; + + // Look through the SelectionDAG patterns we found, possibly emitting some. + for (const PatternToMatch &Pat : CGP.ptms()) { + ++NumPatternTotal; + if (auto SkipReason = runOnPattern(Pat, OS)) { + if (WarnOnSkippedPatterns) { + PrintWarning(Pat.getSrcRecord()->getLoc(), + "Skipped pattern: " + SkipReason->Reason); + } + ++NumPatternSkipped; + } + } + + OS << " return false;\n}\n"; +} + +//===----------------------------------------------------------------------===// + +namespace llvm { +void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) { + GlobalISelEmitter(RK).run(OS); +} +} // End llvm namespace diff --git a/gnu/llvm/utils/TableGen/InstrInfoEmitter.cpp b/gnu/llvm/utils/TableGen/InstrInfoEmitter.cpp index 02461cc0508..ab7d964cd67 100644 --- a/gnu/llvm/utils/TableGen/InstrInfoEmitter.cpp +++ b/gnu/llvm/utils/TableGen/InstrInfoEmitter.cpp @@ -13,22 +13,29 @@ //===----------------------------------------------------------------------===// #include "CodeGenDAGPatterns.h" +#include "CodeGenInstruction.h" #include "CodeGenSchedule.h" #include "CodeGenTarget.h" #include "SequenceToOffsetTable.h" #include "TableGenBackends.h" +#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/raw_ostream.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" -#include <algorithm> -#include <cstdio> +#include <cassert> +#include <cstdint> #include <map> +#include <string> +#include <utility> #include <vector> using namespace llvm; namespace { + class InstrInfoEmitter { RecordKeeper &Records; CodeGenDAGPatterns CDP; @@ -50,7 +57,7 @@ private: /// and instruction operand indices as their values. The values of this map /// are lists of instruction names. typedef std::map<std::map<unsigned, unsigned>, - std::vector<std::string> > OpNameMapTy; + std::vector<std::string>> OpNameMapTy; typedef std::map<std::string, unsigned>::iterator StrUintMapIter; void emitRecord(const CodeGenInstruction &Inst, unsigned Num, Record *InstrInfo, @@ -70,6 +77,7 @@ private: void EmitOperandInfo(raw_ostream &OS, OperandInfoMapTy &OperandInfoIDs); std::vector<std::string> GetOperandInfo(const CodeGenInstruction &Inst); }; + } // end anonymous namespace static void PrintDefList(const std::vector<Record*> &Uses, @@ -106,7 +114,7 @@ InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) { for (unsigned j = 0, e = Op.MINumOperands; j != e; ++j) { OperandList.push_back(Op); - Record *OpR = cast<DefInit>(MIOI->getArg(j))->getDef(); + auto *OpR = cast<DefInit>(MIOI->getArg(j))->getDef(); OperandList.back().Rec = OpR; } } @@ -202,7 +210,6 @@ void InstrInfoEmitter::initOperandMapData( const std::string &Namespace, std::map<std::string, unsigned> &Operands, OpNameMapTy &OperandMap) { - unsigned NumOperands = 0; for (const CodeGenInstruction *Inst : NumberedInstructions) { if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable")) @@ -217,7 +224,8 @@ void InstrInfoEmitter::initOperandMapData( } OpList[I->second] = Info.MIOperandNo; } - OperandMap[OpList].push_back(Namespace + "::" + Inst->TheDef->getName()); + OperandMap[OpList].push_back(Namespace + "::" + + Inst->TheDef->getName().str()); } } @@ -235,7 +243,6 @@ void InstrInfoEmitter::initOperandMapData( void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS, const CodeGenTarget &Target, ArrayRef<const CodeGenInstruction*> NumberedInstructions) { - const std::string &Namespace = Target.getInstNamespace(); std::string OpNameNS = "OpName"; // Map of operand names to their enumeration value. This will be used to @@ -300,7 +307,6 @@ void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS, OS << "} // end namespace " << Namespace << "\n"; OS << "} // end namespace llvm\n"; OS << "#endif //GET_INSTRINFO_NAMED_OPS\n\n"; - } /// Generate an enum for all the operand types for this target, under the @@ -429,7 +435,7 @@ void InstrInfoEmitter::run(raw_ostream &OS) { OS << "struct " << ClassName << " : public TargetInstrInfo {\n" << " explicit " << ClassName << "(int CFSetupOpcode = -1, int CFDestroyOpcode = -1, int CatchRetOpcode = -1, int ReturnOpcode = -1);\n" - << " ~" << ClassName << "() override {}\n" + << " ~" << ClassName << "() override = default;\n" << "};\n"; OS << "} // end llvm namespace\n"; @@ -482,6 +488,7 @@ void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num, if (Inst.isCompare) OS << "|(1ULL<<MCID::Compare)"; if (Inst.isMoveImm) OS << "|(1ULL<<MCID::MoveImm)"; if (Inst.isBitcast) OS << "|(1ULL<<MCID::Bitcast)"; + if (Inst.isAdd) OS << "|(1ULL<<MCID::Add)"; if (Inst.isSelect) OS << "|(1ULL<<MCID::Select)"; if (Inst.isBarrier) OS << "|(1ULL<<MCID::Barrier)"; if (Inst.hasDelaySlot) OS << "|(1ULL<<MCID::DelaySlot)"; @@ -514,7 +521,7 @@ void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num, PrintFatalError("no TSFlags?"); uint64_t Value = 0; for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) { - if (BitInit *Bit = dyn_cast<BitInit>(TSF->getBit(i))) + if (const auto *Bit = dyn_cast<BitInit>(TSF->getBit(i))) Value |= uint64_t(Bit->getValue()) << i; else PrintFatalError("Invalid TSFlags bit in " + Inst.TheDef->getName()); @@ -561,7 +568,6 @@ void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num, // emitEnums - Print out enum values for all of the instructions. void InstrInfoEmitter::emitEnums(raw_ostream &OS) { - OS << "#ifdef GET_INSTRINFO_ENUM\n"; OS << "#undef GET_INSTRINFO_ENUM\n"; diff --git a/gnu/llvm/utils/TableGen/IntrinsicEmitter.cpp b/gnu/llvm/utils/TableGen/IntrinsicEmitter.cpp index a676159e494..33256ccba46 100644 --- a/gnu/llvm/utils/TableGen/IntrinsicEmitter.cpp +++ b/gnu/llvm/utils/TableGen/IntrinsicEmitter.cpp @@ -213,10 +213,11 @@ enum IIT_Info { IIT_HALF_VEC_ARG = 30, IIT_SAME_VEC_WIDTH_ARG = 31, IIT_PTR_TO_ARG = 32, - IIT_VEC_OF_PTRS_TO_ELT = 33, - IIT_I128 = 34, - IIT_V512 = 35, - IIT_V1024 = 36 + IIT_PTR_TO_ELT = 33, + IIT_VEC_OF_PTRS_TO_ELT = 34, + IIT_I128 = 35, + IIT_V512 = 36, + IIT_V1024 = 37 }; @@ -251,7 +252,7 @@ static void EncodeFixedValueType(MVT::SimpleValueType VT, } #if defined(_MSC_VER) && !defined(__clang__) -#pragma optimize("",off) // MSVC 2010 optimizer can't deal with this function. +#pragma optimize("",off) // MSVC 2015 optimizer can't deal with this function. #endif static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes, @@ -277,6 +278,8 @@ static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes, Sig.push_back(IIT_PTR_TO_ARG); else if (R->isSubClassOf("LLVMVectorOfPointersToElt")) Sig.push_back(IIT_VEC_OF_PTRS_TO_ELT); + else if (R->isSubClassOf("LLVMPointerToElt")) + Sig.push_back(IIT_PTR_TO_ELT); else Sig.push_back(IIT_ARG); return Sig.push_back((Number << 3) | ArgCodes[Number]); @@ -287,10 +290,10 @@ static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes, unsigned Tmp = 0; switch (VT) { default: break; - case MVT::iPTRAny: ++Tmp; // FALL THROUGH. - case MVT::vAny: ++Tmp; // FALL THROUGH. - case MVT::fAny: ++Tmp; // FALL THROUGH. - case MVT::iAny: ++Tmp; // FALL THROUGH. + case MVT::iPTRAny: ++Tmp; LLVM_FALLTHROUGH; + case MVT::vAny: ++Tmp; LLVM_FALLTHROUGH; + case MVT::fAny: ++Tmp; LLVM_FALLTHROUGH; + case MVT::iAny: ++Tmp; LLVM_FALLTHROUGH; case MVT::Any: { // If this is an "any" valuetype, then the type is the type of the next // type in the list specified to getIntrinsic(). @@ -643,6 +646,18 @@ void IntrinsicEmitter::EmitAttributes(const CodeGenIntrinsicTable &Ints, OS << ","; OS << "Attribute::ReadOnly"; break; + case CodeGenIntrinsic::ReadInaccessibleMem: + if (addComma) + OS << ","; + OS << "Attribute::ReadOnly,"; + OS << "Attribute::InaccessibleMemOnly"; + break; + case CodeGenIntrinsic::ReadInaccessibleMemOrArgMem: + if (addComma) + OS << ","; + OS << "Attribute::ReadOnly,"; + OS << "Attribute::InaccessibleMemOrArgMemOnly"; + break; case CodeGenIntrinsic::WriteArgMem: if (addComma) OS << ","; @@ -654,11 +669,32 @@ void IntrinsicEmitter::EmitAttributes(const CodeGenIntrinsicTable &Ints, OS << ","; OS << "Attribute::WriteOnly"; break; + case CodeGenIntrinsic::WriteInaccessibleMem: + if (addComma) + OS << ","; + OS << "Attribute::WriteOnly,"; + OS << "Attribute::InaccessibleMemOnly"; + break; + case CodeGenIntrinsic::WriteInaccessibleMemOrArgMem: + if (addComma) + OS << ","; + OS << "Attribute::WriteOnly,"; + OS << "Attribute::InaccessibleMemOrArgOnly"; + break; case CodeGenIntrinsic::ReadWriteArgMem: if (addComma) OS << ","; OS << "Attribute::ArgMemOnly"; break; + case CodeGenIntrinsic::ReadWriteInaccessibleMem: + if (addComma) + OS << ","; + OS << "Attribute::InaccessibleMemOnly"; + break; + case CodeGenIntrinsic::ReadWriteInaccessibleMemOrArgMem: + if (addComma) + OS << ","; + OS << "Attribute::InaccessibleMemOrArgMemOnly"; case CodeGenIntrinsic::ReadWriteMem: break; } @@ -714,11 +750,11 @@ void IntrinsicEmitter::EmitIntrinsicToBuiltinMap( if (TargetOnly) { OS << "static " << TargetPrefix << "Intrinsic::ID " << "getIntrinsicFor" << CompilerName << "Builtin(const char " - << "*TargetPrefixStr, const char *BuiltinNameStr) {\n"; + << "*TargetPrefixStr, StringRef BuiltinNameStr) {\n"; } else { OS << "Intrinsic::ID Intrinsic::getIntrinsicFor" << CompilerName << "Builtin(const char " - << "*TargetPrefixStr, const char *BuiltinNameStr) {\n"; + << "*TargetPrefixStr, StringRef BuiltinNameStr) {\n"; } OS << " static const char BuiltinNames[] = {\n"; Table.EmitCharArray(OS); @@ -730,13 +766,11 @@ void IntrinsicEmitter::EmitIntrinsicToBuiltinMap( OS << " const char *getName() const {\n"; OS << " return &BuiltinNames[StrTabOffset];\n"; OS << " }\n"; - OS << " bool operator<(const char *RHS) const {\n"; - OS << " return strcmp(getName(), RHS) < 0;\n"; + OS << " bool operator<(StringRef RHS) const {\n"; + OS << " return strncmp(getName(), RHS.data(), RHS.size()) < 0;\n"; OS << " }\n"; OS << " };\n"; - - OS << " StringRef BuiltinName(BuiltinNameStr);\n"; OS << " StringRef TargetPrefix(TargetPrefixStr);\n\n"; // Note: this could emit significantly better code if we cared. @@ -759,7 +793,7 @@ void IntrinsicEmitter::EmitIntrinsicToBuiltinMap( OS << " std::end(" << I->first << "Names),\n"; OS << " BuiltinNameStr);\n"; OS << " if (I != std::end(" << I->first << "Names) &&\n"; - OS << " strcmp(I->getName(), BuiltinNameStr) == 0)\n"; + OS << " I->getName() == BuiltinNameStr)\n"; OS << " return I->IntrinID;\n"; OS << " }\n"; } diff --git a/gnu/llvm/utils/TableGen/PseudoLoweringEmitter.cpp b/gnu/llvm/utils/TableGen/PseudoLoweringEmitter.cpp index 01e41d1060e..63bdd36235a 100644 --- a/gnu/llvm/utils/TableGen/PseudoLoweringEmitter.cpp +++ b/gnu/llvm/utils/TableGen/PseudoLoweringEmitter.cpp @@ -177,10 +177,10 @@ void PseudoLoweringEmitter::evaluateExpansion(Record *Rec) { if (OperandMap[Insn.Operands[i].MIOperandNo].Kind != OpData::Operand) continue; StringMap<unsigned>::iterator SourceOp = - SourceOperands.find(Dag->getArgName(i)); + SourceOperands.find(Dag->getArgNameStr(i)); if (SourceOp == SourceOperands.end()) PrintFatalError(Rec->getLoc(), - "Pseudo output operand '" + Dag->getArgName(i) + + "Pseudo output operand '" + Dag->getArgNameStr(i) + "' has no matching source operand."); // Map the source operand to the destination operand index for each // MachineInstr operand. diff --git a/gnu/llvm/utils/TableGen/RegisterInfoEmitter.cpp b/gnu/llvm/utils/TableGen/RegisterInfoEmitter.cpp index 9bb988f30f1..b75be13c048 100644 --- a/gnu/llvm/utils/TableGen/RegisterInfoEmitter.cpp +++ b/gnu/llvm/utils/TableGen/RegisterInfoEmitter.cpp @@ -15,6 +15,7 @@ #include "CodeGenRegisters.h" #include "CodeGenTarget.h" +#include "Types.h" #include "SequenceToOffsetTable.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/BitVector.h" @@ -103,7 +104,7 @@ void RegisterInfoEmitter::runEnums(raw_ostream &OS, OS << "namespace llvm {\n\n"; OS << "class MCRegisterClass;\n" - << "extern const MCRegisterClass " << Namespace + << "extern const MCRegisterClass " << Target.getName() << "MCRegisterClasses[];\n\n"; if (!Namespace.empty()) @@ -177,15 +178,6 @@ static void printInt(raw_ostream &OS, int Val) { OS << Val; } -static const char *getMinimalTypeForRange(uint64_t Range) { - assert(Range < 0xFFFFFFFFULL && "Enum too large"); - if (Range > 0xFFFF) - return "uint32_t"; - if (Range > 0xFF) - return "uint16_t"; - return "uint8_t"; -} - void RegisterInfoEmitter:: EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank, const std::string &ClassName) { @@ -264,8 +256,9 @@ EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank, OS << "// Get the register unit pressure limit for this dimension.\n" << "// This limit must be adjusted dynamically for reserved registers.\n" << "unsigned " << ClassName << "::\n" - << "getRegPressureSetLimit(const MachineFunction &MF, unsigned Idx) const {\n" - << " static const " << getMinimalTypeForRange(MaxRegUnitWeight) + << "getRegPressureSetLimit(const MachineFunction &MF, unsigned Idx) const " + "{\n" + << " static const " << getMinimalTypeForRange(MaxRegUnitWeight, 32) << " PressureLimitTable[] = {\n"; for (unsigned i = 0; i < NumSets; ++i ) { const RegUnitSet &RegUnits = RegBank.getRegSetAt(i); @@ -306,7 +299,7 @@ EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank, << "/// Returns a -1 terminated array of pressure set IDs\n" << "const int* " << ClassName << "::\n" << "getRegClassPressureSets(const TargetRegisterClass *RC) const {\n"; - OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size()-1) + OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size() - 1, 32) << " RCSetStartTable[] = {\n "; for (unsigned i = 0, e = NumRCs; i != e; ++i) { OS << PSetsSeqs.get(PSets[i]) << ","; @@ -322,7 +315,7 @@ EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank, << "getRegUnitPressureSets(unsigned RegUnit) const {\n" << " assert(RegUnit < " << RegBank.getNumNativeRegUnits() << " && \"invalid register unit\");\n"; - OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size()-1) + OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size() - 1, 32) << " RUSetStartTable[] = {\n "; for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits(); UnitIdx < UnitEnd; ++UnitIdx) { @@ -585,7 +578,7 @@ static void printSubRegIndex(raw_ostream &OS, const CodeGenSubRegIndex *Idx) { // 0 differential which means we can't encode repeated elements. typedef SmallVector<uint16_t, 4> DiffVec; -typedef SmallVector<unsigned, 4> MaskVec; +typedef SmallVector<LaneBitmask, 4> MaskVec; // Differentially encode a sequence of numbers into V. The starting value and // terminating 0 are not added to V, so it will have the same size as List. @@ -618,8 +611,8 @@ static void printDiff16(raw_ostream &OS, uint16_t Val) { OS << Val; } -static void printMask(raw_ostream &OS, unsigned Val) { - OS << format("0x%08X", Val); +static void printMask(raw_ostream &OS, LaneBitmask Val) { + OS << "LaneBitmask(0x" << PrintLaneMask(Val) << ')'; } // Try to combine Idx's compose map into Vec if it is compatible. @@ -683,15 +676,15 @@ RegisterInfoEmitter::emitComposeSubRegIndices(raw_ostream &OS, // Output the row map if there is multiple rows. if (Rows.size() > 1) { - OS << " static const " << getMinimalTypeForRange(Rows.size()) << " RowMap[" - << SubRegIndicesSize << "] = {\n "; + OS << " static const " << getMinimalTypeForRange(Rows.size(), 32) + << " RowMap[" << SubRegIndicesSize << "] = {\n "; for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i) OS << RowMap[i] << ", "; OS << "\n };\n"; } // Output the rows. - OS << " static const " << getMinimalTypeForRange(SubRegIndicesSize + 1) + OS << " static const " << getMinimalTypeForRange(SubRegIndicesSize + 1, 32) << " Rows[" << Rows.size() << "][" << SubRegIndicesSize << "] = {\n"; for (unsigned r = 0, re = Rows.size(); r != re; ++r) { OS << " { "; @@ -746,7 +739,7 @@ RegisterInfoEmitter::emitComposeSubRegIndexLaneMask(raw_ostream &OS, } OS << " struct MaskRolOp {\n" - " unsigned Mask;\n" + " LaneBitmask Mask;\n" " uint8_t RotateLeft;\n" " };\n" " static const MaskRolOp LaneMaskComposeSequences[] = {\n"; @@ -756,9 +749,10 @@ RegisterInfoEmitter::emitComposeSubRegIndexLaneMask(raw_ostream &OS, const SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s]; for (size_t p = 0, pe = Sequence.size(); p != pe; ++p) { const MaskRolPair &P = Sequence[p]; - OS << format("{ 0x%08X, %2u }, ", P.Mask, P.RotateLeft); + printMask(OS << "{ ", P.Mask); + OS << format(", %2u }, ", P.RotateLeft); } - OS << "{ 0, 0 }"; + OS << "{ LaneBitmask::getNone(), 0 }"; if (s+1 != se) OS << ", "; OS << " // Sequence " << Idx << "\n"; @@ -781,12 +775,13 @@ RegisterInfoEmitter::emitComposeSubRegIndexLaneMask(raw_ostream &OS, " const {\n" " --IdxA; assert(IdxA < " << SubRegIndices.size() << " && \"Subregister index out of bounds\");\n" - " LaneBitmask Result = 0;\n" - " for (const MaskRolOp *Ops = CompositeSequences[IdxA]; Ops->Mask != 0; ++Ops)" - " {\n" - " LaneBitmask Masked = LaneMask & Ops->Mask;\n" - " Result |= (Masked << Ops->RotateLeft) & 0xFFFFFFFF;\n" - " Result |= (Masked >> ((32 - Ops->RotateLeft) & 0x1F));\n" + " LaneBitmask Result;\n" + " for (const MaskRolOp *Ops = CompositeSequences[IdxA]; Ops->Mask.any(); ++Ops) {\n" + " LaneBitmask::Type M = LaneMask.getAsInteger() & Ops->Mask.getAsInteger();\n" + " if (unsigned S = Ops->RotateLeft)\n" + " Result |= LaneBitmask((M << S) | (M >> (LaneBitmask::BitWidth - S)));\n" + " else\n" + " Result |= LaneBitmask(M);\n" " }\n" " return Result;\n" "}\n\n"; @@ -797,12 +792,13 @@ RegisterInfoEmitter::emitComposeSubRegIndexLaneMask(raw_ostream &OS, " LaneMask &= getSubRegIndexLaneMask(IdxA);\n" " --IdxA; assert(IdxA < " << SubRegIndices.size() << " && \"Subregister index out of bounds\");\n" - " LaneBitmask Result = 0;\n" - " for (const MaskRolOp *Ops = CompositeSequences[IdxA]; Ops->Mask != 0; ++Ops)" - " {\n" - " LaneBitmask Rotated = (LaneMask >> Ops->RotateLeft) |\n" - " ((LaneMask << ((32 - Ops->RotateLeft) & 0x1F)) & 0xFFFFFFFF);\n" - " Result |= Rotated & Ops->Mask;\n" + " LaneBitmask Result;\n" + " for (const MaskRolOp *Ops = CompositeSequences[IdxA]; Ops->Mask.any(); ++Ops) {\n" + " LaneBitmask::Type M = LaneMask.getAsInteger();\n" + " if (unsigned S = Ops->RotateLeft)\n" + " Result |= LaneBitmask((M >> S) | (M << (LaneBitmask::BitWidth - S)));\n" + " else\n" + " Result |= LaneBitmask(M);\n" " }\n" " return Result;\n" "}\n\n"; @@ -901,8 +897,8 @@ RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target, LaneMaskVec.insert(LaneMaskVec.begin(), RUMasks.begin(), RUMasks.end()); // Terminator mask should not be used inside of the list. #ifndef NDEBUG - for (unsigned M : LaneMaskVec) { - assert(M != ~0u && "terminator mask should not be part of the list"); + for (LaneBitmask M : LaneMaskVec) { + assert(!M.all() && "terminator mask should not be part of the list"); } #endif LaneMaskSeqs.add(LaneMaskVec); @@ -923,8 +919,8 @@ RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target, OS << "};\n\n"; // Emit the shared table of regunit lane mask sequences. - OS << "extern const unsigned " << TargetName << "LaneMaskLists[] = {\n"; - LaneMaskSeqs.emit(OS, printMask, "~0u"); + OS << "extern const LaneBitmask " << TargetName << "LaneMaskLists[] = {\n"; + LaneMaskSeqs.emit(OS, printMask, "LaneBitmask::getAll()"); OS << "};\n\n"; // Emit the table of sub-register indexes. @@ -1204,9 +1200,10 @@ RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target, OS << "\" };\n\n"; // Emit SubRegIndex lane masks, including 0. - OS << "\nstatic const unsigned SubRegIndexLaneMaskTable[] = {\n ~0u,\n"; + OS << "\nstatic const LaneBitmask SubRegIndexLaneMaskTable[] = {\n LaneBitmask::getAll(),\n"; for (const auto &Idx : SubRegIndices) { - OS << format(" 0x%08x, // ", Idx.LaneMask) << Idx.getName() << '\n'; + printMask(OS << " ", Idx.LaneMask); + OS << ", // " << Idx.getName() << '\n'; } OS << " };\n\n"; @@ -1324,9 +1321,9 @@ RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target, << "MCRegisterClasses[" << RC.getName() << "RegClassID],\n " << "VTLists + " << VTSeqs.get(RC.VTs) << ",\n " << RC.getName() << "SubClassMask,\n SuperRegIdxSeqs + " - << SuperRegIdxSeqs.get(SuperRegIdxLists[RC.EnumValue]) << ",\n " - << format("0x%08x,\n ", RC.LaneMask) - << (unsigned)RC.AllocationPriority << ",\n " + << SuperRegIdxSeqs.get(SuperRegIdxLists[RC.EnumValue]) << ",\n "; + printMask(OS, RC.LaneMask); + OS << ",\n " << (unsigned)RC.AllocationPriority << ",\n " << (RC.HasDisjunctSubRegs?"true":"false") << ", /* HasDisjunctSubRegs */\n " << (RC.CoveredBySubRegs?"true":"false") @@ -1368,7 +1365,7 @@ RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target, OS << "};\n"; // End of register descriptors... - std::string ClassName = Target.getName() + "GenRegisterInfo"; + std::string ClassName = Target.getName().str() + "GenRegisterInfo"; auto SubRegIndicesSize = std::distance(SubRegIndices.begin(), SubRegIndices.end()); @@ -1415,7 +1412,7 @@ RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target, // Emit the constructor of the class... OS << "extern const MCRegisterDesc " << TargetName << "RegDesc[];\n"; OS << "extern const MCPhysReg " << TargetName << "RegDiffLists[];\n"; - OS << "extern const unsigned " << TargetName << "LaneMaskLists[];\n"; + OS << "extern const LaneBitmask " << TargetName << "LaneMaskLists[];\n"; OS << "extern const char " << TargetName << "RegStrings[];\n"; OS << "extern const char " << TargetName << "RegClassStrings[];\n"; OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2];\n"; @@ -1430,8 +1427,8 @@ RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target, << "(unsigned RA, unsigned DwarfFlavour, unsigned EHFlavour, unsigned PC)\n" << " : TargetRegisterInfo(" << TargetName << "RegInfoDesc" << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() <<",\n" - << " SubRegIndexNameTable, SubRegIndexLaneMaskTable, 0x"; - OS.write_hex(RegBank.CoveringLanes); + << " SubRegIndexNameTable, SubRegIndexLaneMaskTable, "; + printMask(OS, RegBank.CoveringLanes); OS << ") {\n" << " InitMCRegisterInfo(" << TargetName << "RegDesc, " << Regs.size() + 1 << ", RA, PC,\n " << TargetName diff --git a/gnu/llvm/utils/TableGen/SearchableTableEmitter.cpp b/gnu/llvm/utils/TableGen/SearchableTableEmitter.cpp index 8c1b8804d17..80f0b0d4aaf 100644 --- a/gnu/llvm/utils/TableGen/SearchableTableEmitter.cpp +++ b/gnu/llvm/utils/TableGen/SearchableTableEmitter.cpp @@ -193,7 +193,7 @@ void SearchableTableEmitter::emitLookupFunction(StringRef Name, StringRef Field, } else { // Make sure the result is null terminated because it's going via "char *". OS << " std::string CanonicalVal = " << Field << ".upper();\n"; - OS << " " << PairType << " Val = {CanonicalVal.data(), 0};\n"; + OS << " " << PairType << " Val = {CanonicalVal.c_str(), 0};\n"; } OS << " ArrayRef<" << PairType << "> Table(" << Name << "sBy" << Field @@ -206,7 +206,7 @@ void SearchableTableEmitter::emitLookupFunction(StringRef Name, StringRef Field, OS << ",\n "; OS << "[](const " << PairType << " &LHS, const " << PairType << " &RHS) {\n"; - OS << " return StringRef(LHS.first) < StringRef(RHS.first);\n"; + OS << " return std::strcmp(LHS.first, RHS.first) < 0;\n"; OS << " });\n\n"; } diff --git a/gnu/llvm/utils/TableGen/SubtargetEmitter.cpp b/gnu/llvm/utils/TableGen/SubtargetEmitter.cpp index 228882177bd..bf7b392b15e 100644 --- a/gnu/llvm/utils/TableGen/SubtargetEmitter.cpp +++ b/gnu/llvm/utils/TableGen/SubtargetEmitter.cpp @@ -14,7 +14,9 @@ #include "CodeGenTarget.h" #include "CodeGenSchedule.h" #include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringRef.h" #include "llvm/MC/MCInstrItineraries.h" #include "llvm/MC/MCSchedule.h" #include "llvm/MC/SubtargetFeature.h" @@ -27,6 +29,7 @@ #include <algorithm> #include <cassert> #include <cstdint> +#include <iterator> #include <map> #include <string> #include <vector> @@ -42,7 +45,7 @@ class SubtargetEmitter { // The SchedClassDesc table indexes into a global write resource table, write // latency table, and read advance table. struct SchedClassTables { - std::vector<std::vector<MCSchedClassDesc> > ProcSchedClasses; + std::vector<std::vector<MCSchedClassDesc>> ProcSchedClasses; std::vector<MCWriteProcResEntry> WriteProcResources; std::vector<MCWriteLatencyEntry> WriteLatencies; std::vector<std::string> WriterNames; @@ -81,12 +84,12 @@ class SubtargetEmitter { Record *ItinData, std::string &ItinString, unsigned NOperandCycles); void EmitStageAndOperandCycleData(raw_ostream &OS, - std::vector<std::vector<InstrItinerary> > + std::vector<std::vector<InstrItinerary>> &ProcItinLists); void EmitItineraries(raw_ostream &OS, - std::vector<std::vector<InstrItinerary> > + std::vector<std::vector<InstrItinerary>> &ProcItinLists); - void EmitProcessorProp(raw_ostream &OS, const Record *R, const char *Name, + void EmitProcessorProp(raw_ostream &OS, const Record *R, StringRef Name, char Separator); void EmitProcessorResources(const CodeGenProcModel &ProcModel, raw_ostream &OS); @@ -294,7 +297,7 @@ void SubtargetEmitter::FormItineraryStageString(const std::string &Name, // For each unit for (unsigned j = 0, M = UnitList.size(); j < M;) { // Add name and bitwise or - ItinString += Name + "FU::" + UnitList[j]->getName(); + ItinString += Name + "FU::" + UnitList[j]->getName().str(); if (++j < M) ItinString += " | "; } @@ -341,7 +344,7 @@ void SubtargetEmitter::FormItineraryBypassString(const std::string &Name, unsigned N = BypassList.size(); unsigned i = 0; for (; i < N;) { - ItinString += Name + "Bypass::" + BypassList[i]->getName(); + ItinString += Name + "Bypass::" + BypassList[i]->getName().str(); if (++i < NOperandCycles) ItinString += ", "; } for (; i < NOperandCycles;) { @@ -357,9 +360,8 @@ void SubtargetEmitter::FormItineraryBypassString(const std::string &Name, // void SubtargetEmitter:: EmitStageAndOperandCycleData(raw_ostream &OS, - std::vector<std::vector<InstrItinerary> > + std::vector<std::vector<InstrItinerary>> &ProcItinLists) { - // Multiple processor models may share an itinerary record. Emit it once. SmallPtrSet<Record*, 8> ItinsDefSet; @@ -498,7 +500,7 @@ EmitStageAndOperandCycleData(raw_ostream &OS, int NumUOps = ItinData ? ItinData->getValueAsInt("NumMicroOps") : 0; InstrItinerary Intinerary = { NumUOps, FindStage, FindStage + NStages, FindOperandCycle, - FindOperandCycle + NOperandCycles}; + FindOperandCycle + NOperandCycles }; // Inject - empty slots will be 0, 0 ItinList[SchedClassIdx] = Intinerary; @@ -530,13 +532,12 @@ EmitStageAndOperandCycleData(raw_ostream &OS, // void SubtargetEmitter:: EmitItineraries(raw_ostream &OS, - std::vector<std::vector<InstrItinerary> > &ProcItinLists) { - + std::vector<std::vector<InstrItinerary>> &ProcItinLists) { // Multiple processor models may share an itinerary record. Emit it once. SmallPtrSet<Record*, 8> ItinsDefSet; // For each processor's machine model - std::vector<std::vector<InstrItinerary> >::iterator + std::vector<std::vector<InstrItinerary>>::iterator ProcItinListsIter = ProcItinLists.begin(); for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(), PE = SchedModels.procModelEnd(); PI != PE; ++PI, ++ProcItinListsIter) { @@ -587,7 +588,7 @@ EmitItineraries(raw_ostream &OS, // value defined in the C++ header. The Record is null if the processor does not // define a model. void SubtargetEmitter::EmitProcessorProp(raw_ostream &OS, const Record *R, - const char *Name, char Separator) { + StringRef Name, char Separator) { OS << " "; int V = R ? R->getValueAsInt(Name) : -1; if (V >= 0) @@ -783,8 +784,7 @@ void SubtargetEmitter::ExpandProcResources(RecVec &PRVec, RecVec SuperResources = PR->getValueAsListOfDefs("Resources"); RecIter SubI = SubResources.begin(), SubE = SubResources.end(); for( ; SubI != SubE; ++SubI) { - if (std::find(SuperResources.begin(), SuperResources.end(), *SubI) - == SuperResources.end()) { + if (!is_contained(SuperResources, *SubI)) { break; } } @@ -827,9 +827,7 @@ void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel, HasVariants = true; break; } - IdxIter PIPos = std::find(TI->ProcIndices.begin(), - TI->ProcIndices.end(), ProcModel.Index); - if (PIPos != TI->ProcIndices.end()) { + if (is_contained(TI->ProcIndices, ProcModel.Index)) { HasVariants = true; break; } @@ -844,9 +842,7 @@ void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel, // If ProcIndices contains 0, this class applies to all processors. assert(!SC.ProcIndices.empty() && "expect at least one procidx"); if (SC.ProcIndices[0] != 0) { - IdxIter PIPos = std::find(SC.ProcIndices.begin(), - SC.ProcIndices.end(), ProcModel.Index); - if (PIPos == SC.ProcIndices.end()) + if (!is_contained(SC.ProcIndices, ProcModel.Index)) continue; } IdxVec Writes = SC.Writes; @@ -873,8 +869,7 @@ void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel, // Check this processor's itinerary class resources. for (Record *I : ProcModel.ItinRWDefs) { RecVec Matched = I->getValueAsListOfDefs("MatchedItinClasses"); - if (std::find(Matched.begin(), Matched.end(), SC.ItinClassDef) - != Matched.end()) { + if (is_contained(Matched, SC.ItinClassDef)) { SchedModels.findRWs(I->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads); break; @@ -1246,7 +1241,7 @@ void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) { << "#endif\n"; if (SchedModels.hasItineraries()) { - std::vector<std::vector<InstrItinerary> > ProcItinLists; + std::vector<std::vector<InstrItinerary>> ProcItinLists; // Emit the stage data EmitStageAndOperandCycleData(OS, ProcItinLists); EmitItineraries(OS, ProcItinLists); @@ -1430,13 +1425,13 @@ void SubtargetEmitter::run(raw_ostream &OS) { << Target << "WriteProcResTable, " << Target << "WriteLatencyTable, " << Target << "ReadAdvanceTable, "; + OS << '\n'; OS.indent(22); if (SchedModels.hasItineraries()) { - OS << '\n'; OS.indent(22); OS << Target << "Stages, " << Target << "OperandCycles, " << Target << "ForwardingPaths"; } else - OS << "0, 0, 0"; + OS << "nullptr, nullptr, nullptr"; OS << ");\n}\n\n"; OS << "} // end namespace llvm\n\n"; @@ -1516,7 +1511,7 @@ void SubtargetEmitter::run(raw_ostream &OS) { << Target << "OperandCycles, " << Target << "ForwardingPaths"; } else - OS << "0, 0, 0"; + OS << "nullptr, nullptr, nullptr"; OS << ") {}\n\n"; EmitSchedModelHelpers(ClassName, OS); diff --git a/gnu/llvm/utils/TableGen/SubtargetFeatureInfo.cpp b/gnu/llvm/utils/TableGen/SubtargetFeatureInfo.cpp new file mode 100644 index 00000000000..7db8813050f --- /dev/null +++ b/gnu/llvm/utils/TableGen/SubtargetFeatureInfo.cpp @@ -0,0 +1,119 @@ +//===- SubtargetFeatureInfo.cpp - Helpers for subtarget features ----------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "SubtargetFeatureInfo.h" + +#include "Types.h" +#include "llvm/TableGen/Record.h" + +#include <map> + +using namespace llvm; + +void SubtargetFeatureInfo::dump() const { + errs() << getEnumName() << " " << Index << "\n"; + TheDef->dump(); +} + +std::vector<std::pair<Record *, SubtargetFeatureInfo>> +SubtargetFeatureInfo::getAll(const RecordKeeper &Records) { + std::vector<std::pair<Record *, SubtargetFeatureInfo>> SubtargetFeatures; + std::vector<Record *> AllPredicates = + Records.getAllDerivedDefinitions("Predicate"); + for (Record *Pred : AllPredicates) { + // Ignore predicates that are not intended for the assembler. + // + // The "AssemblerMatcherPredicate" string should be promoted to an argument + // if we re-use the machinery for non-assembler purposes in future. + if (!Pred->getValueAsBit("AssemblerMatcherPredicate")) + continue; + + if (Pred->getName().empty()) + PrintFatalError(Pred->getLoc(), "Predicate has no name!"); + + SubtargetFeatures.emplace_back( + Pred, SubtargetFeatureInfo(Pred, SubtargetFeatures.size())); + } + return SubtargetFeatures; +} + +void SubtargetFeatureInfo::emitSubtargetFeatureFlagEnumeration( + std::map<Record *, SubtargetFeatureInfo, LessRecordByID> &SubtargetFeatures, + raw_ostream &OS) { + OS << "// Flags for subtarget features that participate in " + << "instruction matching.\n"; + OS << "enum SubtargetFeatureFlag : " + << getMinimalTypeForEnumBitfield(SubtargetFeatures.size()) << " {\n"; + for (const auto &SF : SubtargetFeatures) { + const SubtargetFeatureInfo &SFI = SF.second; + OS << " " << SFI.getEnumName() << " = (1ULL << " << SFI.Index << "),\n"; + } + OS << " Feature_None = 0\n"; + OS << "};\n\n"; +} + +void SubtargetFeatureInfo::emitNameTable( + std::map<Record *, SubtargetFeatureInfo, LessRecordByID> &SubtargetFeatures, + raw_ostream &OS) { + OS << "static const char *SubtargetFeatureNames[] = {\n"; + for (const auto &SF : SubtargetFeatures) { + const SubtargetFeatureInfo &SFI = SF.second; + OS << " \"" << SFI.getEnumName() << "\",\n"; + } + // A small number of targets have no predicates. Null terminate the array to + // avoid a zero-length array. + OS << " nullptr\n" + << "};\n\n"; +} + +void SubtargetFeatureInfo::emitComputeAvailableFeatures( + StringRef TargetName, StringRef ClassName, StringRef FuncName, + std::map<Record *, SubtargetFeatureInfo, LessRecordByID> &SubtargetFeatures, + raw_ostream &OS) { + OS << "uint64_t " << TargetName << ClassName << "::\n" + << FuncName << "(const FeatureBitset& FB) const {\n"; + OS << " uint64_t Features = 0;\n"; + for (const auto &SF : SubtargetFeatures) { + const SubtargetFeatureInfo &SFI = SF.second; + + OS << " if ("; + std::string CondStorage = + SFI.TheDef->getValueAsString("AssemblerCondString"); + StringRef Conds = CondStorage; + std::pair<StringRef, StringRef> Comma = Conds.split(','); + bool First = true; + do { + if (!First) + OS << " && "; + + bool Neg = false; + StringRef Cond = Comma.first; + if (Cond[0] == '!') { + Neg = true; + Cond = Cond.substr(1); + } + + OS << "("; + if (Neg) + OS << "!"; + OS << "FB[" << TargetName << "::" << Cond << "])"; + + if (Comma.second.empty()) + break; + + First = false; + Comma = Comma.second.split(','); + } while (true); + + OS << ")\n"; + OS << " Features |= " << SFI.getEnumName() << ";\n"; + } + OS << " return Features;\n"; + OS << "}\n\n"; +} diff --git a/gnu/llvm/utils/TableGen/SubtargetFeatureInfo.h b/gnu/llvm/utils/TableGen/SubtargetFeatureInfo.h new file mode 100644 index 00000000000..99f380f2a1d --- /dev/null +++ b/gnu/llvm/utils/TableGen/SubtargetFeatureInfo.h @@ -0,0 +1,72 @@ +//===- SubtargetFeatureInfo.h - Helpers for subtarget features ------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_UTIL_TABLEGEN_SUBTARGETFEATUREINFO_H +#define LLVM_UTIL_TABLEGEN_SUBTARGETFEATUREINFO_H + +#include "llvm/TableGen/Error.h" +#include "llvm/TableGen/Record.h" + +#include <map> +#include <string> +#include <vector> + +namespace llvm { +class Record; +class RecordKeeper; + +/// Helper class for storing information on a subtarget feature which +/// participates in instruction matching. +struct SubtargetFeatureInfo { + /// \brief The predicate record for this feature. + Record *TheDef; + + /// \brief An unique index assigned to represent this feature. + uint64_t Index; + + SubtargetFeatureInfo(Record *D, uint64_t Idx) : TheDef(D), Index(Idx) {} + + /// \brief The name of the enumerated constant identifying this feature. + std::string getEnumName() const { + return "Feature_" + TheDef->getName().str(); + } + + void dump() const; + static std::vector<std::pair<Record *, SubtargetFeatureInfo>> + getAll(const RecordKeeper &Records); + + /// Emit the subtarget feature flag definitions. + static void emitSubtargetFeatureFlagEnumeration( + std::map<Record *, SubtargetFeatureInfo, LessRecordByID> + &SubtargetFeatures, + raw_ostream &OS); + + static void emitNameTable(std::map<Record *, SubtargetFeatureInfo, + LessRecordByID> &SubtargetFeatures, + raw_ostream &OS); + + /// Emit the function to compute the list of available features given a + /// subtarget. + /// + /// \param TargetName The name of the target as used in class prefixes (e.g. + /// <TargetName>Subtarget) + /// \param ClassName The name of the class (without the <Target> prefix) + /// that will contain the generated functions. + /// \param FuncName The name of the function to emit. + /// \param SubtargetFeatures A map of TableGen records to the + /// SubtargetFeatureInfo equivalent. + static void emitComputeAvailableFeatures( + StringRef TargetName, StringRef ClassName, StringRef FuncName, + std::map<Record *, SubtargetFeatureInfo, LessRecordByID> + &SubtargetFeatures, + raw_ostream &OS); +}; +} // end namespace llvm + +#endif // LLVM_UTIL_TABLEGEN_SUBTARGETFEATUREINFO_H diff --git a/gnu/llvm/utils/TableGen/TableGen.cpp b/gnu/llvm/utils/TableGen/TableGen.cpp index 24dbe5d3a28..79a773161e4 100644 --- a/gnu/llvm/utils/TableGen/TableGen.cpp +++ b/gnu/llvm/utils/TableGen/TableGen.cpp @@ -45,6 +45,7 @@ enum ActionType { GenCTags, GenAttributes, GenSearchableTables, + GenGlobalISel, }; namespace { @@ -92,7 +93,8 @@ namespace { "Generate attributes"), clEnumValN(GenSearchableTables, "gen-searchable-tables", "Generate generic binary-searchable table"), - clEnumValEnd)); + clEnumValN(GenGlobalISel, "gen-global-isel", + "Generate GlobalISel selector"))); cl::opt<std::string> Class("class", cl::desc("Print Enum list for this class"), @@ -178,6 +180,9 @@ bool LLVMTableGenMain(raw_ostream &OS, RecordKeeper &Records) { case GenSearchableTables: EmitSearchableTables(Records, OS); break; + case GenGlobalISel: + EmitGlobalISel(Records, OS); + break; } return false; diff --git a/gnu/llvm/utils/TableGen/TableGenBackends.h b/gnu/llvm/utils/TableGen/TableGenBackends.h index 51e017fe659..eb306d28180 100644 --- a/gnu/llvm/utils/TableGen/TableGenBackends.h +++ b/gnu/llvm/utils/TableGen/TableGenBackends.h @@ -80,6 +80,7 @@ void EmitOptParser(RecordKeeper &RK, raw_ostream &OS); void EmitCTags(RecordKeeper &RK, raw_ostream &OS); void EmitAttributes(RecordKeeper &RK, raw_ostream &OS); void EmitSearchableTables(RecordKeeper &RK, raw_ostream &OS); +void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS); } // End llvm namespace diff --git a/gnu/llvm/utils/TableGen/Types.cpp b/gnu/llvm/utils/TableGen/Types.cpp new file mode 100644 index 00000000000..35458296f8f --- /dev/null +++ b/gnu/llvm/utils/TableGen/Types.cpp @@ -0,0 +1,44 @@ +//===- Types.cpp - Helper for the selection of C++ data types. ------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "Types.h" + +// For LLVM_ATTRIBUTE_UNUSED +#include "llvm/Support/Compiler.h" + +#include <cassert> + +using namespace llvm; + +const char *llvm::getMinimalTypeForRange(uint64_t Range, unsigned MaxSize LLVM_ATTRIBUTE_UNUSED) { + // TODO: The original callers only used 32 and 64 so these are the only + // values permitted. Rather than widen the supported values we should + // allow 64 for the callers that currently use 32 and remove the + // argument altogether. + assert((MaxSize == 32 || MaxSize == 64) && "Unexpected size"); + assert(MaxSize <= 64 && "Unexpected size"); + assert(((MaxSize > 32) ? Range <= 0xFFFFFFFFFFFFFFFFULL + : Range <= 0xFFFFFFFFULL) && + "Enum too large"); + + if (Range > 0xFFFFFFFFULL) + return "uint64_t"; + if (Range > 0xFFFF) + return "uint32_t"; + if (Range > 0xFF) + return "uint16_t"; + return "uint8_t"; +} + +const char *llvm::getMinimalTypeForEnumBitfield(uint64_t Size) { + uint64_t MaxIndex = Size; + if (MaxIndex > 0) + MaxIndex--; + return getMinimalTypeForRange(1ULL << MaxIndex); +} diff --git a/gnu/llvm/utils/TableGen/Types.h b/gnu/llvm/utils/TableGen/Types.h new file mode 100644 index 00000000000..d511b7eae6e --- /dev/null +++ b/gnu/llvm/utils/TableGen/Types.h @@ -0,0 +1,25 @@ +//===- Types.h - Helper for the selection of C++ types. ---------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_UTILS_TABLEGEN_TYPES_H +#define LLVM_UTILS_TABLEGEN_TYPES_H + +#include <cstdint> + +namespace llvm { +/// Returns the smallest unsigned integer type that can hold the given range. +/// MaxSize indicates the largest size of integer to consider (in bits) and only +/// supports values of at least 32. +const char *getMinimalTypeForRange(uint64_t Range, unsigned MaxSize = 64); + +/// Returns the smallest unsigned integer type that can hold the given bitfield. +const char *getMinimalTypeForEnumBitfield(uint64_t Size); +} + +#endif diff --git a/gnu/llvm/utils/TableGen/X86RecognizableInstr.cpp b/gnu/llvm/utils/TableGen/X86RecognizableInstr.cpp index ca937d09726..4736c4e510d 100644 --- a/gnu/llvm/utils/TableGen/X86RecognizableInstr.cpp +++ b/gnu/llvm/utils/TableGen/X86RecognizableInstr.cpp @@ -23,96 +23,100 @@ using namespace llvm; #define MRM_MAPPING \ - MAP(C0, 32) \ - MAP(C1, 33) \ - MAP(C2, 34) \ - MAP(C3, 35) \ - MAP(C4, 36) \ - MAP(C5, 37) \ - MAP(C6, 38) \ - MAP(C7, 39) \ - MAP(C8, 40) \ - MAP(C9, 41) \ - MAP(CA, 42) \ - MAP(CB, 43) \ - MAP(CC, 44) \ - MAP(CD, 45) \ - MAP(CE, 46) \ - MAP(CF, 47) \ - MAP(D0, 48) \ - MAP(D1, 49) \ - MAP(D2, 50) \ - MAP(D3, 51) \ - MAP(D4, 52) \ - MAP(D5, 53) \ - MAP(D6, 54) \ - MAP(D7, 55) \ - MAP(D8, 56) \ - MAP(D9, 57) \ - MAP(DA, 58) \ - MAP(DB, 59) \ - MAP(DC, 60) \ - MAP(DD, 61) \ - MAP(DE, 62) \ - MAP(DF, 63) \ - MAP(E0, 64) \ - MAP(E1, 65) \ - MAP(E2, 66) \ - MAP(E3, 67) \ - MAP(E4, 68) \ - MAP(E5, 69) \ - MAP(E6, 70) \ - MAP(E7, 71) \ - MAP(E8, 72) \ - MAP(E9, 73) \ - MAP(EA, 74) \ - MAP(EB, 75) \ - MAP(EC, 76) \ - MAP(ED, 77) \ - MAP(EE, 78) \ - MAP(EF, 79) \ - MAP(F0, 80) \ - MAP(F1, 81) \ - MAP(F2, 82) \ - MAP(F3, 83) \ - MAP(F4, 84) \ - MAP(F5, 85) \ - MAP(F6, 86) \ - MAP(F7, 87) \ - MAP(F8, 88) \ - MAP(F9, 89) \ - MAP(FA, 90) \ - MAP(FB, 91) \ - MAP(FC, 92) \ - MAP(FD, 93) \ - MAP(FE, 94) \ - MAP(FF, 95) + MAP(C0, 64) \ + MAP(C1, 65) \ + MAP(C2, 66) \ + MAP(C3, 67) \ + MAP(C4, 68) \ + MAP(C5, 69) \ + MAP(C6, 70) \ + MAP(C7, 71) \ + MAP(C8, 72) \ + MAP(C9, 73) \ + MAP(CA, 74) \ + MAP(CB, 75) \ + MAP(CC, 76) \ + MAP(CD, 77) \ + MAP(CE, 78) \ + MAP(CF, 79) \ + MAP(D0, 80) \ + MAP(D1, 81) \ + MAP(D2, 82) \ + MAP(D3, 83) \ + MAP(D4, 84) \ + MAP(D5, 85) \ + MAP(D6, 86) \ + MAP(D7, 87) \ + MAP(D8, 88) \ + MAP(D9, 89) \ + MAP(DA, 90) \ + MAP(DB, 91) \ + MAP(DC, 92) \ + MAP(DD, 93) \ + MAP(DE, 94) \ + MAP(DF, 95) \ + MAP(E0, 96) \ + MAP(E1, 97) \ + MAP(E2, 98) \ + MAP(E3, 99) \ + MAP(E4, 100) \ + MAP(E5, 101) \ + MAP(E6, 102) \ + MAP(E7, 103) \ + MAP(E8, 104) \ + MAP(E9, 105) \ + MAP(EA, 106) \ + MAP(EB, 107) \ + MAP(EC, 108) \ + MAP(ED, 109) \ + MAP(EE, 110) \ + MAP(EF, 111) \ + MAP(F0, 112) \ + MAP(F1, 113) \ + MAP(F2, 114) \ + MAP(F3, 115) \ + MAP(F4, 116) \ + MAP(F5, 117) \ + MAP(F6, 118) \ + MAP(F7, 119) \ + MAP(F8, 120) \ + MAP(F9, 121) \ + MAP(FA, 122) \ + MAP(FB, 123) \ + MAP(FC, 124) \ + MAP(FD, 125) \ + MAP(FE, 126) \ + MAP(FF, 127) // A clone of X86 since we can't depend on something that is generated. namespace X86Local { enum { - Pseudo = 0, - RawFrm = 1, - AddRegFrm = 2, - MRMDestReg = 3, - MRMDestMem = 4, - MRMSrcReg = 5, - MRMSrcMem = 6, - RawFrmMemOffs = 7, - RawFrmSrc = 8, - RawFrmDst = 9, - RawFrmDstSrc = 10, - RawFrmImm8 = 11, - RawFrmImm16 = 12, - MRMXr = 14, MRMXm = 15, - MRM0r = 16, MRM1r = 17, MRM2r = 18, MRM3r = 19, - MRM4r = 20, MRM5r = 21, MRM6r = 22, MRM7r = 23, - MRM0m = 24, MRM1m = 25, MRM2m = 26, MRM3m = 27, - MRM4m = 28, MRM5m = 29, MRM6m = 30, MRM7m = 31, + Pseudo = 0, + RawFrm = 1, + AddRegFrm = 2, + RawFrmMemOffs = 3, + RawFrmSrc = 4, + RawFrmDst = 5, + RawFrmDstSrc = 6, + RawFrmImm8 = 7, + RawFrmImm16 = 8, + MRMDestMem = 32, + MRMSrcMem = 33, + MRMSrcMem4VOp3 = 34, + MRMSrcMemOp4 = 35, + MRMXm = 39, + MRM0m = 40, MRM1m = 41, MRM2m = 42, MRM3m = 43, + MRM4m = 44, MRM5m = 45, MRM6m = 46, MRM7m = 47, + MRMDestReg = 48, + MRMSrcReg = 49, + MRMSrcReg4VOp3 = 50, + MRMSrcRegOp4 = 51, + MRMXr = 55, + MRM0r = 56, MRM1r = 57, MRM2r = 58, MRM3r = 59, + MRM4r = 60, MRM5r = 61, MRM6r = 62, MRM7r = 63, #define MAP(from, to) MRM_##from = to, MRM_MAPPING #undef MAP - lastMRM }; enum { @@ -138,19 +142,6 @@ namespace X86Local { using namespace X86Disassembler; -/// isRegFormat - Indicates whether a particular form requires the Mod field of -/// the ModR/M byte to be 0b11. -/// -/// @param form - The form of the instruction. -/// @return - true if the form implies that Mod must be 0b11, false -/// otherwise. -static bool isRegFormat(uint8_t form) { - return (form == X86Local::MRMDestReg || - form == X86Local::MRMSrcReg || - form == X86Local::MRMXr || - (form >= X86Local::MRM0r && form <= X86Local::MRM7r)); -} - /// byteFromBitsInit - Extracts a value at most 8 bits in width from a BitsInit. /// Useful for switch statements and the like. /// @@ -212,9 +203,7 @@ RecognizableInstr::RecognizableInstr(DisassemblerTables &tables, AdSize = byteFromRec(Rec, "AdSizeBits"); HasREX_WPrefix = Rec->getValueAsBit("hasREX_WPrefix"); HasVEX_4V = Rec->getValueAsBit("hasVEX_4V"); - HasVEX_4VOp3 = Rec->getValueAsBit("hasVEX_4VOp3"); HasVEX_WPrefix = Rec->getValueAsBit("hasVEX_WPrefix"); - HasMemOp4Prefix = Rec->getValueAsBit("hasMemOp4Prefix"); IgnoresVEX_L = Rec->getValueAsBit("ignoresVEX_L"); HasEVEX_L2Prefix = Rec->getValueAsBit("hasEVEX_L2"); HasEVEX_K = Rec->getValueAsBit("hasEVEX_K"); @@ -565,7 +554,7 @@ void RecognizableInstr::emitInstructionSpecifier() { // Given the set of prefix bits, how many additional operands does the // instruction have? unsigned additionalOperands = 0; - if (HasVEX_4V || HasVEX_4VOp3) + if (HasVEX_4V) ++additionalOperands; if (HasEVEX_K) ++additionalOperands; @@ -666,19 +655,27 @@ void RecognizableInstr::emitInstructionSpecifier() { // in ModRMVEX and the one above the one in the VEX.VVVV field HANDLE_OPERAND(vvvvRegister) - if (HasMemOp4Prefix) - HANDLE_OPERAND(immediate) - HANDLE_OPERAND(rmRegister) - - if (HasVEX_4VOp3) - HANDLE_OPERAND(vvvvRegister) - - if (!HasMemOp4Prefix) - HANDLE_OPTIONAL(immediate) + HANDLE_OPTIONAL(immediate) HANDLE_OPTIONAL(immediate) // above might be a register in 7:4 HANDLE_OPTIONAL(immediate) break; + case X86Local::MRMSrcReg4VOp3: + assert(numPhysicalOperands == 3 && + "Unexpected number of operands for MRMSrcRegFrm"); + HANDLE_OPERAND(roRegister) + HANDLE_OPERAND(rmRegister) + HANDLE_OPERAND(vvvvRegister) + break; + case X86Local::MRMSrcRegOp4: + assert(numPhysicalOperands >= 4 && numPhysicalOperands <= 5 && + "Unexpected number of operands for MRMSrcRegOp4Frm"); + HANDLE_OPERAND(roRegister) + HANDLE_OPERAND(vvvvRegister) + HANDLE_OPERAND(immediate) // Register in imm[7:4] + HANDLE_OPERAND(rmRegister) + HANDLE_OPTIONAL(immediate) + break; case X86Local::MRMSrcMem: // Operand 1 is a register operand in the Reg/Opcode field. // Operand 2 is a memory operand (possibly SIB-extended) @@ -699,18 +696,26 @@ void RecognizableInstr::emitInstructionSpecifier() { // in ModRMVEX and the one above the one in the VEX.VVVV field HANDLE_OPERAND(vvvvRegister) - if (HasMemOp4Prefix) - HANDLE_OPERAND(immediate) - HANDLE_OPERAND(memory) - - if (HasVEX_4VOp3) - HANDLE_OPERAND(vvvvRegister) - - if (!HasMemOp4Prefix) - HANDLE_OPTIONAL(immediate) + HANDLE_OPTIONAL(immediate) HANDLE_OPTIONAL(immediate) // above might be a register in 7:4 break; + case X86Local::MRMSrcMem4VOp3: + assert(numPhysicalOperands == 3 && + "Unexpected number of operands for MRMSrcMemFrm"); + HANDLE_OPERAND(roRegister) + HANDLE_OPERAND(memory) + HANDLE_OPERAND(vvvvRegister) + break; + case X86Local::MRMSrcMemOp4: + assert(numPhysicalOperands >= 4 && numPhysicalOperands <= 5 && + "Unexpected number of operands for MRMSrcMemOp4Frm"); + HANDLE_OPERAND(roRegister) + HANDLE_OPERAND(vvvvRegister) + HANDLE_OPERAND(immediate) // Register in imm[7:4] + HANDLE_OPERAND(memory) + HANDLE_OPTIONAL(immediate) + break; case X86Local::MRMXr: case X86Local::MRM0r: case X86Local::MRM1r: @@ -841,13 +846,31 @@ void RecognizableInstr::emitDecodePath(DisassemblerTables &tables) const { } switch (Form) { - default: + default: llvm_unreachable("Invalid form!"); + case X86Local::Pseudo: llvm_unreachable("Pseudo should not be emitted!"); + case X86Local::RawFrm: + case X86Local::AddRegFrm: + case X86Local::RawFrmMemOffs: + case X86Local::RawFrmSrc: + case X86Local::RawFrmDst: + case X86Local::RawFrmDstSrc: + case X86Local::RawFrmImm8: + case X86Local::RawFrmImm16: filter = new DumbFilter(); break; - case X86Local::MRMDestReg: case X86Local::MRMDestMem: - case X86Local::MRMSrcReg: case X86Local::MRMSrcMem: - case X86Local::MRMXr: case X86Local::MRMXm: - filter = new ModFilter(isRegFormat(Form)); + case X86Local::MRMDestReg: + case X86Local::MRMSrcReg: + case X86Local::MRMSrcReg4VOp3: + case X86Local::MRMSrcRegOp4: + case X86Local::MRMXr: + filter = new ModFilter(true); + break; + case X86Local::MRMDestMem: + case X86Local::MRMSrcMem: + case X86Local::MRMSrcMem4VOp3: + case X86Local::MRMSrcMemOp4: + case X86Local::MRMXm: + filter = new ModFilter(false); break; case X86Local::MRM0r: case X86Local::MRM1r: case X86Local::MRM2r: case X86Local::MRM3r: diff --git a/gnu/llvm/utils/TableGen/X86RecognizableInstr.h b/gnu/llvm/utils/TableGen/X86RecognizableInstr.h index f6f50065f70..2e611587cc3 100644 --- a/gnu/llvm/utils/TableGen/X86RecognizableInstr.h +++ b/gnu/llvm/utils/TableGen/X86RecognizableInstr.h @@ -55,14 +55,10 @@ private: bool HasREX_WPrefix; /// The hasVEX_4V field from the record bool HasVEX_4V; - /// The hasVEX_4VOp3 field from the record - bool HasVEX_4VOp3; /// The hasVEX_WPrefix field from the record bool HasVEX_WPrefix; /// Inferred from the operands; indicates whether the L bit in the VEX prefix is set bool HasVEX_LPrefix; - /// The hasMemOp4Prefix field from the record - bool HasMemOp4Prefix; /// The ignoreVEX_L field from the record bool IgnoresVEX_L; /// The hasEVEX_L2Prefix field from the record diff --git a/gnu/llvm/utils/extract_symbols.py b/gnu/llvm/utils/extract_symbols.py index 9f467a7d055..96ae24c608e 100755 --- a/gnu/llvm/utils/extract_symbols.py +++ b/gnu/llvm/utils/extract_symbols.py @@ -128,8 +128,12 @@ def should_keep_microsoft_symbol(symbol, calling_convention_decoration): if match: return match.group(1) return symbol - # Function template instantiations start with ?$, discard them as it's - # assumed that the definition is public + # Function template instantiations start with ?$; keep the instantiations of + # clang::Type::getAs, as some of them are explipict specializations that are + # defined in clang's lib/AST/Type.cpp; discard the rest as it's assumed that + # the definition is public + elif re.match('\?\?\$getAs@.+@Type@clang@@', symbol): + return symbol elif symbol.startswith('??$'): return None # Deleting destructors start with ?_G or ?_E and can be discarded because @@ -195,8 +199,12 @@ def should_keep_itanium_symbol(symbol, calling_convention_decoration): # defined in headers and not required to be kept if re.match('[CD][123]', names[-1][0]) and names[-2][1]: return None - # Discard function template instantiations as it's assumed that the - # definition is public + # Keep the instantiations of clang::Type::getAs, as some of them are + # explipict specializations that are defined in clang's lib/AST/Type.cpp; + # discard any other function template instantiations as it's assumed that + # the definition is public + elif symbol.startswith('_ZNK5clang4Type5getAs'): + return symbol elif names[-1][1]: return None # Keep llvm:: and clang:: names diff --git a/gnu/llvm/utils/gdb-scripts/prettyprinters.py b/gnu/llvm/utils/gdb-scripts/prettyprinters.py index 0dbc7af3e46..5385e16246b 100644 --- a/gnu/llvm/utils/gdb-scripts/prettyprinters.py +++ b/gnu/llvm/utils/gdb-scripts/prettyprinters.py @@ -46,6 +46,8 @@ class SmallVectorPrinter: self.cur = self.cur + 1 return '[%d]' % count, cur.dereference() + __next__ = next + def __init__(self, val): self.val = val @@ -86,6 +88,8 @@ class ArrayRefPrinter: self.cur = self.cur + 1 return '[%d]' % count, cur.dereference() + __next__ = next + def __init__(self, val): self.val = val @@ -99,9 +103,102 @@ class ArrayRefPrinter: def display_hint (self): return 'array' +class OptionalPrinter: + """Print an llvm::Optional object.""" + + def __init__(self, value): + self.value = value + + class _iterator: + def __init__(self, member, empty): + self.member = member + self.done = empty + + def __iter__(self): + return self + + def next(self): + if self.done: + raise StopIteration + self.done = True + return ('value', self.member.dereference()) + + def children(self): + if not self.value['hasVal']: + return self._iterator('', True) + return self._iterator(self.value['storage']['buffer'].address.cast(self.value.type.template_argument(0).pointer()), False) + + def to_string(self): + return 'llvm::Optional is %sinitialized' % ('' if self.value['hasVal'] else 'not ') + +class DenseMapPrinter: + "Print a DenseMap" + + class _iterator: + def __init__(self, key_info_t, begin, end): + self.key_info_t = key_info_t + self.cur = begin + self.end = end + self.advancePastEmptyBuckets() + self.first = True + + def __iter__(self): + return self + + def advancePastEmptyBuckets(self): + # disabled until the comments below can be addressed + # keeping as notes/posterity/hints for future contributors + return + n = self.key_info_t.name + is_equal = gdb.parse_and_eval(n + '::isEqual') + empty = gdb.parse_and_eval(n + '::getEmptyKey()') + tombstone = gdb.parse_and_eval(n + '::getTombstoneKey()') + # the following is invalid, GDB fails with: + # Python Exception <class 'gdb.error'> Attempt to take address of value + # not located in memory. + # because isEqual took parameter (for the unsigned long key I was testing) + # by const ref, and GDB + # It's also not entirely general - we should be accessing the "getFirst()" + # member function, not the 'first' member variable, but I've yet to figure + # out how to find/call member functions (especially (const) overloaded + # ones) on a gdb.Value. + while self.cur != self.end and (is_equal(self.cur.dereference()['first'], empty) or is_equal(self.cur.dereference()['first'], tombstone)): + self.cur = self.cur + 1 + + def next(self): + if self.cur == self.end: + raise StopIteration + cur = self.cur + v = cur.dereference()['first' if self.first else 'second'] + if not self.first: + self.cur = self.cur + 1 + self.advancePastEmptyBuckets() + self.first = True + else: + self.first = False + return 'x', v + + def __init__(self, val): + self.val = val + + def children(self): + t = self.val.type.template_argument(3).pointer() + begin = self.val['Buckets'].cast(t) + end = (begin + self.val['NumBuckets']).cast(t) + return self._iterator(self.val.type.template_argument(2), begin, end) + + def to_string(self): + return 'llvm::DenseMap with %d elements' % (self.val['NumEntries']) + + def display_hint(self): + return 'map' + + pp = gdb.printing.RegexpCollectionPrettyPrinter("LLVMSupport") pp.add_printer('llvm::SmallString', '^llvm::SmallString<.*>$', SmallStringPrinter) pp.add_printer('llvm::StringRef', '^llvm::StringRef$', StringRefPrinter) pp.add_printer('llvm::SmallVectorImpl', '^llvm::SmallVector(Impl)?<.*>$', SmallVectorPrinter) pp.add_printer('llvm::ArrayRef', '^llvm::(Const)?ArrayRef<.*>$', ArrayRefPrinter) +pp.add_printer('llvm::Optional', '^llvm::Optional<.*>$', OptionalPrinter) +pp.add_printer('llvm::DenseMap', '^llvm::DenseMap<.*>$', DenseMapPrinter) gdb.printing.register_pretty_printer(gdb.current_objfile(), pp) diff --git a/gnu/llvm/utils/git-svn/git-llvm b/gnu/llvm/utils/git-svn/git-llvm new file mode 100755 index 00000000000..3dd3ff7dc39 --- /dev/null +++ b/gnu/llvm/utils/git-svn/git-llvm @@ -0,0 +1,288 @@ +#!/usr/bin/env python +# +# ======- git-llvm - LLVM Git Help Integration ---------*- python -*--========# +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +# ==------------------------------------------------------------------------==# + +""" +git-llvm integration +==================== + +This file provides integration for git. +""" + +from __future__ import print_function +import argparse +import collections +import contextlib +import errno +import os +import re +import subprocess +import sys +import tempfile +import time +assert sys.version_info >= (2, 7) + + +# It's *almost* a straightforward mapping from the monorepo to svn... +GIT_TO_SVN_DIR = { + d: (d + '/trunk') + for d in [ + 'clang-tools-extra', + 'compiler-rt', + 'dragonegg', + 'klee', + 'libclc', + 'libcxx', + 'libcxxabi', + 'lld', + 'lldb', + 'llvm', + 'polly', + ] +} +GIT_TO_SVN_DIR.update({'clang': 'cfe/trunk'}) + +VERBOSE = False +QUIET = False + + +def eprint(*args, **kwargs): + print(*args, file=sys.stderr, **kwargs) + + +def log(*args, **kwargs): + if QUIET: + return + print(*args, **kwargs) + + +def log_verbose(*args, **kwargs): + if not VERBOSE: + return + print(*args, **kwargs) + + +def die(msg): + eprint(msg) + sys.exit(1) + + +def first_dirname(d): + while True: + (head, tail) = os.path.split(d) + if not head or head == '/': + return tail + d = head + + +def shell(cmd, strip=True, cwd=None, stdin=None, die_on_failure=True): + log_verbose('Running: %s' % ' '.join(cmd)) + + start = time.time() + p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, stdin=subprocess.PIPE) + stdout, stderr = p.communicate(input=stdin) + elapsed = time.time() - start + + log_verbose('Command took %0.1fs' % elapsed) + + if p.returncode == 0: + if stderr: + eprint('`%s` printed to stderr:' % ' '.join(cmd)) + eprint(stderr.rstrip()) + if strip: + stdout = stdout.rstrip('\r\n') + return stdout + err_msg = '`%s` returned %s' % (' '.join(cmd), p.returncode) + eprint(err_msg) + if stderr: + eprint(stderr.rstrip()) + if die_on_failure: + sys.exit(2) + raise RuntimeError(err_msg) + + +def git(*cmd, **kwargs): + return shell(['git'] + list(cmd), kwargs.get('strip', True)) + + +def svn(cwd, *cmd, **kwargs): + # TODO: Better way to do default arg when we have *cmd? + return shell(['svn'] + list(cmd), cwd=cwd, stdin=kwargs.get('stdin', None)) + + +def get_default_rev_range(): + # Get the branch tracked by the current branch, as set by + # git branch --set-upstream-to See http://serverfault.com/a/352236/38694. + cur_branch = git('rev-parse', '--symbolic-full-name', 'HEAD') + upstream_branch = git('for-each-ref', '--format=%(upstream:short)', + cur_branch) + if not upstream_branch: + upstream_branch = 'origin/master' + + # Get the newest common ancestor between HEAD and our upstream branch. + upstream_rev = git('merge-base', 'HEAD', upstream_branch) + return '%s..' % upstream_rev + + +def get_revs_to_push(rev_range): + if not rev_range: + rev_range = get_default_rev_range() + # Use git show rather than some plumbing command to figure out which revs + # are in rev_range because it handles single revs (HEAD^) and ranges + # (foo..bar) like we want. + revs = git('show', '--reverse', '--quiet', + '--pretty=%h', rev_range).splitlines() + if not revs: + die('Nothing to push: No revs in range %s.' % rev_range) + return revs + + +def clean_and_update_svn(svn_repo): + svn(svn_repo, 'revert', '-R', '.') + + # Unfortunately it appears there's no svn equivalent for git clean, so we + # have to do it ourselves. + for line in svn(svn_repo, 'status').split('\n'): + if not line.startswith('?'): + continue + filename = line[1:].strip() + os.remove(os.path.join(svn_repo, filename)) + + svn(svn_repo, 'update', *list(GIT_TO_SVN_DIR.values())) + + +def svn_init(svn_root): + if not os.path.exists(svn_root): + log('Creating svn staging directory: (%s)' % (svn_root)) + os.makedirs(svn_root) + log('This is a one-time initialization, please be patient for a few' + ' minutes...') + svn(svn_root, 'checkout', '--depth=immediates', + 'https://llvm.org/svn/llvm-project/', '.') + svn(svn_root, 'update', *list(GIT_TO_SVN_DIR.values())) + log("svn staging area ready in '%s'" % svn_root) + if not os.path.isdir(svn_root): + die("Can't initialize svn staging dir (%s)" % svn_root) + + +def svn_push_one_rev(svn_repo, rev, dry_run): + files = git('diff-tree', '--no-commit-id', '--name-only', '-r', + rev).split('\n') + subrepos = {first_dirname(f) for f in files} + if not subrepos: + raise RuntimeError('Empty diff for rev %s?' % rev) + + status = svn(svn_repo, 'status') + if status: + die("Can't push git rev %s because svn status is not empty:\n%s" % + (rev, status)) + + for sr in subrepos: + diff = git('show', '--binary', rev, '--', sr, strip=False) + svn_sr_path = os.path.join(svn_repo, GIT_TO_SVN_DIR[sr]) + # git is the only thing that can handle its own patches... + log_verbose('Apply patch: %s' % diff) + try: + shell(['git', 'apply', '-p2', '-'], cwd=svn_sr_path, stdin=diff, + die_on_failure=False) + except RuntimeError as e: + eprint("Patch doesn't apply: maybe you should try `git pull -r` " + "first?") + sys.exit(2) + + status_lines = svn(svn_repo, 'status').split('\n') + + for l in (l for l in status_lines if l.startswith('?')): + svn(svn_repo, 'add', l[1:].strip()) + for l in (l for l in status_lines if l.startswith('!')): + svn(svn_repo, 'remove', l[1:].strip()) + + # Now we're ready to commit. + commit_msg = git('show', '--pretty=%B', '--quiet', rev) + if not dry_run: + log(svn(svn_repo, 'commit', '-m', commit_msg, '--force-interactive')) + log('Committed %s to svn.' % rev) + else: + log("Would have committed %s to svn, if this weren't a dry run." % rev) + + +def cmd_push(args): + '''Push changes back to SVN: this is extracted from Justin Lebar's script + available here: https://github.com/jlebar/llvm-repo-tools/ + + Note: a current limitation is that git does not track file rename, so they + will show up in SVN as delete+add. + ''' + # Get the git root + git_root = git('rev-parse', '--show-toplevel') + if not os.path.isdir(git_root): + die("Can't find git root dir") + + # Push from the root of the git repo + os.chdir(git_root) + + # We need a staging area for SVN, let's hide it in the .git directory. + dot_git_dir = git('rev-parse', '--git-common-dir') + svn_root = os.path.join(dot_git_dir, 'llvm-upstream-svn') + svn_init(svn_root) + + rev_range = args.rev_range + dry_run = args.dry_run + revs = get_revs_to_push(rev_range) + log('Pushing %d commit%s:\n%s' % + (len(revs), 's' if len(revs) != 1 + else '', '\n'.join(' ' + git('show', '--oneline', '--quiet', c) + for c in revs))) + for r in revs: + clean_and_update_svn(svn_root) + svn_push_one_rev(svn_root, r, dry_run) + + +if __name__ == '__main__': + argv = sys.argv[1:] + p = argparse.ArgumentParser( + prog='git llvm', formatter_class=argparse.RawDescriptionHelpFormatter, + description=__doc__) + subcommands = p.add_subparsers(title='subcommands', + description='valid subcommands', + help='additional help') + verbosity_group = p.add_mutually_exclusive_group() + verbosity_group.add_argument('-q', '--quiet', action='store_true', + help='print less information') + verbosity_group.add_argument('-v', '--verbose', action='store_true', + help='print more information') + + parser_push = subcommands.add_parser( + 'push', description=cmd_push.__doc__, + help='push changes back to the LLVM SVN repository') + parser_push.add_argument( + '-n', + '--dry-run', + dest='dry_run', + action='store_true', + help='Do everything other than commit to svn. Leaves junk in the svn ' + 'repo, so probably will not work well if you try to commit more ' + 'than one rev.') + parser_push.add_argument( + 'rev_range', + metavar='GIT_REVS', + type=str, + nargs='?', + help="revs to push (default: everything not in the branch's " + 'upstream, or not in origin/master if the branch lacks ' + 'an explicit upstream)') + parser_push.set_defaults(func=cmd_push) + args = p.parse_args(argv) + VERBOSE = args.verbose + QUIET = args.quiet + + # Dispatch to the right subcommand + args.func(args) diff --git a/gnu/llvm/utils/lit/README.txt b/gnu/llvm/utils/lit/README.txt index 8cf48404759..12cf7ae3949 100644 --- a/gnu/llvm/utils/lit/README.txt +++ b/gnu/llvm/utils/lit/README.txt @@ -6,3 +6,36 @@ lit is a portable tool for executing LLVM and Clang style test suites, summarizing their results, and providing indication of failures. lit is designed to be a lightweight testing tool with as simple a user interface as possible. +===================== + Contributing to lit +===================== + +Please browse the Test Suite > lit category in LLVM's Bugzilla for ideas on +what to work on. + +Before submitting patches, run the test suite to ensure nothing has regressed: + + # From within your LLVM source directory. + utils/lit/lit.py \ + --path /path/to/your/llvm/build/bin \ + utils/lit/tests + +Note that lit's tests depend on 'not' and 'FileCheck', LLVM utilities. +You will need to have built LLVM tools in order to run lit's test suite +successfully. + +You'll also want to confirm that lit continues to work when testing LLVM. +Follow the instructions in http://llvm.org/docs/TestingGuide.html to run the +regression test suite: + + make check-llvm + +And be sure to run the llvm-lit wrapper script as well: + + /path/to/your/llvm/build/bin/llvm-lit utils/lit/tests + +Finally, make sure lit works when installed via setuptools: + + python utils/lit/setup.py install + lit --path /path/to/your/llvm/build/bin utils/lit/tests + diff --git a/gnu/llvm/utils/lit/lit.py b/gnu/llvm/utils/lit/lit.py index 851063b3bd1..2c5ecfe1d40 100755 --- a/gnu/llvm/utils/lit/lit.py +++ b/gnu/llvm/utils/lit/lit.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +from lit.main import main + if __name__=='__main__': - import lit - lit.main() + main() diff --git a/gnu/llvm/utils/lit/lit/LitConfig.py b/gnu/llvm/utils/lit/lit/LitConfig.py index 2402221bef1..fc50ffc1039 100644 --- a/gnu/llvm/utils/lit/lit/LitConfig.py +++ b/gnu/llvm/utils/lit/lit/LitConfig.py @@ -23,7 +23,8 @@ class LitConfig(object): useValgrind, valgrindLeakCheck, valgrindArgs, noExecute, debug, isWindows, params, config_prefix = None, - maxIndividualTestTime = 0): + maxIndividualTestTime = 0, + maxFailures = None): # The name of the test runner. self.progname = progname # The items to add to the PATH environment variable. @@ -60,6 +61,7 @@ class LitConfig(object): self.valgrindArgs.extend(self.valgrindUserArgs) self.maxIndividualTestTime = maxIndividualTestTime + self.maxFailures = maxFailures @property def maxIndividualTestTime(self): @@ -81,7 +83,7 @@ class LitConfig(object): # a timeout per test. Check it's available. # See lit.util.killProcessAndChildren() try: - import psutil + import psutil # noqa: F401 except ImportError: self.fatal("Setting a timeout per test requires the" " Python psutil module but it could not be" @@ -132,7 +134,7 @@ class LitConfig(object): # Step out of _write_message, and then out of wrapper. f = f.f_back.f_back file,line,_,_,_ = inspect.getframeinfo(f) - location = '%s:%d' % (os.path.basename(file), line) + location = '%s:%d' % (file, line) sys.stderr.write('%s: %s: %s: %s\n' % (self.progname, location, kind, message)) diff --git a/gnu/llvm/utils/lit/lit/ShUtil.py b/gnu/llvm/utils/lit/lit/ShUtil.py index 1945ba723bc..0b3e0f58c97 100644 --- a/gnu/llvm/utils/lit/lit/ShUtil.py +++ b/gnu/llvm/utils/lit/lit/ShUtil.py @@ -245,111 +245,3 @@ class ShParser: return lhs -### - -import unittest - -class TestShLexer(unittest.TestCase): - def lex(self, str, *args, **kwargs): - return list(ShLexer(str, *args, **kwargs).lex()) - - def test_basic(self): - self.assertEqual(self.lex('a|b>c&d<e;f'), - ['a', ('|',), 'b', ('>',), 'c', ('&',), 'd', - ('<',), 'e', (';',), 'f']) - - def test_redirection_tokens(self): - self.assertEqual(self.lex('a2>c'), - ['a2', ('>',), 'c']) - self.assertEqual(self.lex('a 2>c'), - ['a', ('>',2), 'c']) - - def test_quoting(self): - self.assertEqual(self.lex(""" 'a' """), - ['a']) - self.assertEqual(self.lex(""" "hello\\"world" """), - ['hello"world']) - self.assertEqual(self.lex(""" "hello\\'world" """), - ["hello\\'world"]) - self.assertEqual(self.lex(""" "hello\\\\world" """), - ["hello\\world"]) - self.assertEqual(self.lex(""" he"llo wo"rld """), - ["hello world"]) - self.assertEqual(self.lex(""" a\\ b a\\\\b """), - ["a b", "a\\b"]) - self.assertEqual(self.lex(""" "" "" """), - ["", ""]) - self.assertEqual(self.lex(""" a\\ b """, win32Escapes = True), - ['a\\', 'b']) - -class TestShParse(unittest.TestCase): - def parse(self, str): - return ShParser(str).parse() - - def test_basic(self): - self.assertEqual(self.parse('echo hello'), - Pipeline([Command(['echo', 'hello'], [])], False)) - self.assertEqual(self.parse('echo ""'), - Pipeline([Command(['echo', ''], [])], False)) - self.assertEqual(self.parse("""echo -DFOO='a'"""), - Pipeline([Command(['echo', '-DFOO=a'], [])], False)) - self.assertEqual(self.parse('echo -DFOO="a"'), - Pipeline([Command(['echo', '-DFOO=a'], [])], False)) - - def test_redirection(self): - self.assertEqual(self.parse('echo hello > c'), - Pipeline([Command(['echo', 'hello'], - [((('>'),), 'c')])], False)) - self.assertEqual(self.parse('echo hello > c >> d'), - Pipeline([Command(['echo', 'hello'], [(('>',), 'c'), - (('>>',), 'd')])], False)) - self.assertEqual(self.parse('a 2>&1'), - Pipeline([Command(['a'], [(('>&',2), '1')])], False)) - - def test_pipeline(self): - self.assertEqual(self.parse('a | b'), - Pipeline([Command(['a'], []), - Command(['b'], [])], - False)) - - self.assertEqual(self.parse('a | b | c'), - Pipeline([Command(['a'], []), - Command(['b'], []), - Command(['c'], [])], - False)) - - def test_list(self): - self.assertEqual(self.parse('a ; b'), - Seq(Pipeline([Command(['a'], [])], False), - ';', - Pipeline([Command(['b'], [])], False))) - - self.assertEqual(self.parse('a & b'), - Seq(Pipeline([Command(['a'], [])], False), - '&', - Pipeline([Command(['b'], [])], False))) - - self.assertEqual(self.parse('a && b'), - Seq(Pipeline([Command(['a'], [])], False), - '&&', - Pipeline([Command(['b'], [])], False))) - - self.assertEqual(self.parse('a || b'), - Seq(Pipeline([Command(['a'], [])], False), - '||', - Pipeline([Command(['b'], [])], False))) - - self.assertEqual(self.parse('a && b || c'), - Seq(Seq(Pipeline([Command(['a'], [])], False), - '&&', - Pipeline([Command(['b'], [])], False)), - '||', - Pipeline([Command(['c'], [])], False))) - - self.assertEqual(self.parse('a; b'), - Seq(Pipeline([Command(['a'], [])], False), - ';', - Pipeline([Command(['b'], [])], False))) - -if __name__ == '__main__': - unittest.main() diff --git a/gnu/llvm/utils/lit/lit/Test.py b/gnu/llvm/utils/lit/lit/Test.py index 9c9c47d6321..657a7e8140d 100644 --- a/gnu/llvm/utils/lit/lit/Test.py +++ b/gnu/llvm/utils/lit/lit/Test.py @@ -189,9 +189,9 @@ class Test: def setResult(self, result): if self.result is not None: - raise ArgumentError("test result already set") + raise ValueError("test result already set") if not isinstance(result, Result): - raise ArgumentError("unexpected result type") + raise ValueError("unexpected result type") self.result = result diff --git a/gnu/llvm/utils/lit/lit/TestRunner.py b/gnu/llvm/utils/lit/lit/TestRunner.py index 24d687280c4..942ae38a04c 100644 --- a/gnu/llvm/utils/lit/lit/TestRunner.py +++ b/gnu/llvm/utils/lit/lit/TestRunner.py @@ -140,6 +140,62 @@ def executeShCmd(cmd, shenv, results, timeout=0): return (finalExitCode, timeoutInfo) +def quote_windows_command(seq): + """ + Reimplement Python's private subprocess.list2cmdline for MSys compatibility + + Based on CPython implementation here: + https://hg.python.org/cpython/file/849826a900d2/Lib/subprocess.py#l422 + + Some core util distributions (MSys) don't tokenize command line arguments + the same way that MSVC CRT does. Lit rolls its own quoting logic similar to + the stock CPython logic to paper over these quoting and tokenization rule + differences. + + We use the same algorithm from MSDN as CPython + (http://msdn.microsoft.com/en-us/library/17w5ykft.aspx), but we treat more + characters as needing quoting, such as double quotes themselves. + """ + result = [] + needquote = False + for arg in seq: + bs_buf = [] + + # Add a space to separate this argument from the others + if result: + result.append(' ') + + # This logic differs from upstream list2cmdline. + needquote = (" " in arg) or ("\t" in arg) or ("\"" in arg) or not arg + if needquote: + result.append('"') + + for c in arg: + if c == '\\': + # Don't know if we need to double yet. + bs_buf.append(c) + elif c == '"': + # Double backslashes. + result.append('\\' * len(bs_buf)*2) + bs_buf = [] + result.append('\\"') + else: + # Normal char + if bs_buf: + result.extend(bs_buf) + bs_buf = [] + result.append(c) + + # Add remaining backslashes, if any. + if bs_buf: + result.extend(bs_buf) + + if needquote: + result.extend(bs_buf) + result.append('"') + + return ''.join(result) + def _executeShCmd(cmd, shenv, results, timeoutHelper): if timeoutHelper.timeoutReached(): # Prevent further recursion if the timeout has been hit @@ -315,6 +371,11 @@ def _executeShCmd(cmd, shenv, results, timeoutHelper): named_temp_files.append(f.name) args[i] = f.name + # On Windows, do our own command line quoting for better compatibility + # with some core utility distributions. + if kIsWindows: + args = quote_windows_command(args) + try: procs.append(subprocess.Popen(args, cwd=cmd_shenv.cwd, executable = executable, @@ -406,7 +467,7 @@ def _executeShCmd(cmd, shenv, results, timeoutHelper): data = f.read() except: data = None - if data != None: + if data is not None: output_files.append((name, path, data)) results.append(ShellCommandResult( @@ -494,16 +555,22 @@ def executeScriptInternal(test, litConfig, tmpBase, commands, cwd): # Show the error conditions: if result.exitCode != 0: - out += "error: command failed with exit status: %d\n" % ( - result.exitCode,) + # On Windows, a negative exit code indicates a signal, and those are + # easier to recognize or look up if we print them in hex. + if litConfig.isWindows and result.exitCode < 0: + codeStr = hex(int(result.exitCode & 0xFFFFFFFF)).rstrip("L") + else: + codeStr = str(result.exitCode) + out += "error: command failed with exit status: %s\n" % ( + codeStr,) if litConfig.maxIndividualTestTime > 0: out += 'error: command reached timeout: %s\n' % ( - i, str(result.timeoutReached)) + str(result.timeoutReached),) return out, err, exitCode, timeoutInfo def executeScript(test, litConfig, tmpBase, commands, cwd): - bashPath = litConfig.getBashPath(); + bashPath = litConfig.getBashPath() isWin32CMDEXE = (litConfig.isWindows and not bashPath) script = tmpBase + '.script' if isWin32CMDEXE: @@ -563,7 +630,7 @@ def parseIntegratedTestScriptCommands(source_path, keywords): # version. keywords_re = re.compile( - to_bytes("(%s)(.*)\n" % ("|".join(k for k in keywords),))) + to_bytes("(%s)(.*)\n" % ("|".join(re.escape(k) for k in keywords),))) f = open(source_path, 'rb') try: @@ -590,7 +657,7 @@ def parseIntegratedTestScriptCommands(source_path, keywords): # Python 2, to avoid other code having to differentiate between the # str and unicode types. keyword,ln = match.groups() - yield (line_number, to_string(keyword[:-1].decode('utf-8')), + yield (line_number, to_string(keyword.decode('utf-8')), to_string(ln.decode('utf-8'))) finally: f.close() @@ -672,10 +739,119 @@ def applySubstitutions(script, substitutions): # convert to list before returning. return list(map(processLine, script)) -def parseIntegratedTestScript(test, require_script=True): + +class ParserKind(object): + """ + An enumeration representing the style of an integrated test keyword or + command. + + TAG: A keyword taking no value. Ex 'END.' + COMMAND: A Keyword taking a list of shell commands. Ex 'RUN:' + LIST: A keyword taking a comma separated list of value. Ex 'XFAIL:' + CUSTOM: A keyword with custom parsing semantics. + """ + TAG = 0 + COMMAND = 1 + LIST = 2 + CUSTOM = 3 + + +class IntegratedTestKeywordParser(object): + """A parser for LLVM/Clang style integrated test scripts. + + keyword: The keyword to parse for. It must end in either '.' or ':'. + kind: An value of ParserKind. + parser: A custom parser. This value may only be specified with + ParserKind.CUSTOM. + """ + def __init__(self, keyword, kind, parser=None, initial_value=None): + if not keyword.endswith('.') and not keyword.endswith(':'): + raise ValueError("keyword '%s' must end with either '.' or ':' " + % keyword) + if keyword.endswith('.') and kind in \ + [ParserKind.LIST, ParserKind.COMMAND]: + raise ValueError("Keyword '%s' should end in ':'" % keyword) + + elif keyword.endswith(':') and kind in [ParserKind.TAG]: + raise ValueError("Keyword '%s' should end in '.'" % keyword) + if parser is not None and kind != ParserKind.CUSTOM: + raise ValueError("custom parsers can only be specified with " + "ParserKind.CUSTOM") + self.keyword = keyword + self.kind = kind + self.parsed_lines = [] + self.value = initial_value + self.parser = parser + + if kind == ParserKind.COMMAND: + self.parser = self._handleCommand + elif kind == ParserKind.LIST: + self.parser = self._handleList + elif kind == ParserKind.TAG: + if not keyword.endswith('.'): + raise ValueError("keyword '%s' should end with '.'" % keyword) + self.parser = self._handleTag + elif kind == ParserKind.CUSTOM: + if parser is None: + raise ValueError("ParserKind.CUSTOM requires a custom parser") + self.parser = parser + else: + raise ValueError("Unknown kind '%s'" % kind) + + def parseLine(self, line_number, line): + self.parsed_lines += [(line_number, line)] + self.value = self.parser(line_number, line, self.value) + + def getValue(self): + return self.value + + @staticmethod + def _handleTag(line_number, line, output): + """A helper for parsing TAG type keywords""" + return (not line.strip() or output) + + @staticmethod + def _handleCommand(line_number, line, output): + """A helper for parsing COMMAND type keywords""" + # Trim trailing whitespace. + line = line.rstrip() + # Substitute line number expressions + line = re.sub('%\(line\)', str(line_number), line) + + def replace_line_number(match): + if match.group(1) == '+': + return str(line_number + int(match.group(2))) + if match.group(1) == '-': + return str(line_number - int(match.group(2))) + line = re.sub('%\(line *([\+-]) *(\d+)\)', replace_line_number, line) + # Collapse lines with trailing '\\'. + if output and output[-1][-1] == '\\': + output[-1] = output[-1][:-1] + line + else: + if output is None: + output = [] + output.append(line) + return output + + @staticmethod + def _handleList(line_number, line, output): + """A parser for LIST type keywords""" + if output is None: + output = [] + output.extend([s.strip() for s in line.split(',')]) + return output + + +def parseIntegratedTestScript(test, additional_parsers=[], + require_script=True): """parseIntegratedTestScript - Scan an LLVM/Clang style integrated test script and extract the lines to 'RUN' as well as 'XFAIL' and 'REQUIRES' - and 'UNSUPPORTED' information. If 'require_script' is False an empty script + 'REQUIRES-ANY' and 'UNSUPPORTED' information. + + If additional parsers are specified then the test is also scanned for the + keywords they specify and all matches are passed to the custom parser. + + If 'require_script' is False an empty script may be returned. This can be used for test formats where the actual script is optional or ignored. """ @@ -685,43 +861,36 @@ def parseIntegratedTestScript(test, require_script=True): requires = [] requires_any = [] unsupported = [] - keywords = ['RUN:', 'XFAIL:', 'REQUIRES:', 'REQUIRES-ANY:', - 'UNSUPPORTED:', 'END.'] + builtin_parsers = [ + IntegratedTestKeywordParser('RUN:', ParserKind.COMMAND, + initial_value=script), + IntegratedTestKeywordParser('XFAIL:', ParserKind.LIST, + initial_value=test.xfails), + IntegratedTestKeywordParser('REQUIRES:', ParserKind.LIST, + initial_value=requires), + IntegratedTestKeywordParser('REQUIRES-ANY:', ParserKind.LIST, + initial_value=requires_any), + IntegratedTestKeywordParser('UNSUPPORTED:', ParserKind.LIST, + initial_value=unsupported), + IntegratedTestKeywordParser('END.', ParserKind.TAG) + ] + keyword_parsers = {p.keyword: p for p in builtin_parsers} + for parser in additional_parsers: + if not isinstance(parser, IntegratedTestKeywordParser): + raise ValueError('additional parser must be an instance of ' + 'IntegratedTestKeywordParser') + if parser.keyword in keyword_parsers: + raise ValueError("Parser for keyword '%s' already exists" + % parser.keyword) + keyword_parsers[parser.keyword] = parser + for line_number, command_type, ln in \ - parseIntegratedTestScriptCommands(sourcepath, keywords): - if command_type == 'RUN': - # Trim trailing whitespace. - ln = ln.rstrip() - - # Substitute line number expressions - ln = re.sub('%\(line\)', str(line_number), ln) - def replace_line_number(match): - if match.group(1) == '+': - return str(line_number + int(match.group(2))) - if match.group(1) == '-': - return str(line_number - int(match.group(2))) - ln = re.sub('%\(line *([\+-]) *(\d+)\)', replace_line_number, ln) - - # Collapse lines with trailing '\\'. - if script and script[-1][-1] == '\\': - script[-1] = script[-1][:-1] + ln - else: - script.append(ln) - elif command_type == 'XFAIL': - test.xfails.extend([s.strip() for s in ln.split(',')]) - elif command_type == 'REQUIRES': - requires.extend([s.strip() for s in ln.split(',')]) - elif command_type == 'REQUIRES-ANY': - requires_any.extend([s.strip() for s in ln.split(',')]) - elif command_type == 'UNSUPPORTED': - unsupported.extend([s.strip() for s in ln.split(',')]) - elif command_type == 'END': - # END commands are only honored if the rest of the line is empty. - if not ln.strip(): - break - else: - raise ValueError("unknown script command type: %r" % ( - command_type,)) + parseIntegratedTestScriptCommands(sourcepath, + keyword_parsers.keys()): + parser = keyword_parsers[command_type] + parser.parseLine(line_number, ln) + if command_type == 'END.' and parser.getValue() is True: + break # Verify the script contains a run line. if require_script and not script: @@ -738,26 +907,30 @@ def parseIntegratedTestScript(test, require_script=True): if missing_required_features: msg = ', '.join(missing_required_features) return lit.Test.Result(Test.UNSUPPORTED, - "Test requires the following features: %s" % msg) + "Test requires the following features: %s" + % msg) requires_any_features = [f for f in requires_any if f in test.config.available_features] if requires_any and not requires_any_features: msg = ' ,'.join(requires_any) return lit.Test.Result(Test.UNSUPPORTED, - "Test requires any of the following features: %s" % msg) + "Test requires any of the following features: " + "%s" % msg) unsupported_features = [f for f in unsupported if f in test.config.available_features] if unsupported_features: msg = ', '.join(unsupported_features) - return lit.Test.Result(Test.UNSUPPORTED, - "Test is unsupported with the following features: %s" % msg) + return lit.Test.Result( + Test.UNSUPPORTED, + "Test is unsupported with the following features: %s" % msg) unsupported_targets = [f for f in unsupported if f in test.suite.config.target_triple] if unsupported_targets: - return lit.Test.Result(Test.UNSUPPORTED, - "Test is unsupported with the following triple: %s" % ( - test.suite.config.target_triple,)) + return lit.Test.Result( + Test.UNSUPPORTED, + "Test is unsupported with the following triple: %s" % ( + test.suite.config.target_triple,)) if test.config.limit_to_features: # Check that we have one of the limit_to_features features in requires. @@ -765,11 +938,12 @@ def parseIntegratedTestScript(test, require_script=True): if f in requires] if not limit_to_features_tests: msg = ', '.join(test.config.limit_to_features) - return lit.Test.Result(Test.UNSUPPORTED, - "Test requires one of the limit_to_features features %s" % msg) - + return lit.Test.Result( + Test.UNSUPPORTED, + "Test requires one of the limit_to_features features %s" % msg) return script + def _runShTest(test, litConfig, useExternalSh, script, tmpBase): # Create the output directory if it does not already exist. lit.util.mkdir_p(os.path.dirname(tmpBase)) @@ -786,7 +960,7 @@ def _runShTest(test, litConfig, useExternalSh, script, tmpBase): if exitCode == 0: status = Test.PASS else: - if timeoutInfo == None: + if timeoutInfo is None: status = Test.FAIL else: status = Test.TIMEOUT @@ -795,7 +969,7 @@ def _runShTest(test, litConfig, useExternalSh, script, tmpBase): output = """Script:\n--\n%s\n--\nExit Code: %d\n""" % ( '\n'.join(script), exitCode) - if timeoutInfo != None: + if timeoutInfo is not None: output += """Timeout: %s\n""" % (timeoutInfo,) output += "\n" diff --git a/gnu/llvm/utils/lit/lit/TestingConfig.py b/gnu/llvm/utils/lit/lit/TestingConfig.py index 1e39a000c90..717b53c67fb 100644 --- a/gnu/llvm/utils/lit/lit/TestingConfig.py +++ b/gnu/llvm/utils/lit/lit/TestingConfig.py @@ -1,7 +1,6 @@ import os import sys -OldPy = sys.version_info[0] == 2 and sys.version_info[1] < 7 class TestingConfig: """" @@ -25,7 +24,8 @@ class TestingConfig: pass_vars = ['LIBRARY_PATH', 'LD_LIBRARY_PATH', 'SYSTEMROOT', 'TERM', 'LD_PRELOAD', 'ASAN_OPTIONS', 'UBSAN_OPTIONS', 'LSAN_OPTIONS', 'ADB', 'ANDROID_SERIAL', - 'SANITIZER_IGNORE_CVE_2016_2143'] + 'SANITIZER_IGNORE_CVE_2016_2143', 'TMPDIR', 'TMP', 'TEMP', + 'TEMPDIR', 'AVRLIT_BOARD', 'AVRLIT_PORT'] for var in pass_vars: val = os.environ.get(var, '') # Check for empty string as some variables such as LD_PRELOAD cannot be empty @@ -42,16 +42,6 @@ class TestingConfig: 'TMP' : os.environ.get('TMP',''), }) - # The option to preserve TEMP, TMP, and TMPDIR. - # This is intended to check how many temporary files would be generated - # (and be not cleaned up) in automated builders. - if 'LIT_PRESERVES_TMP' in os.environ: - environment.update({ - 'TEMP' : os.environ.get('TEMP',''), - 'TMP' : os.environ.get('TMP',''), - 'TMPDIR' : os.environ.get('TMPDIR',''), - }) - # Set the default available features based on the LitConfig. available_features = [] if litConfig.useValgrind: @@ -82,13 +72,12 @@ class TestingConfig: # Load the config script data. data = None - if not OldPy: - f = open(path) - try: - data = f.read() - except: - litConfig.fatal('unable to load config file: %r' % (path,)) - f.close() + f = open(path) + try: + data = f.read() + except: + litConfig.fatal('unable to load config file: %r' % (path,)) + f.close() # Execute the config script to initialize the object. cfg_globals = dict(globals()) @@ -96,10 +85,7 @@ class TestingConfig: cfg_globals['lit_config'] = litConfig cfg_globals['__file__'] = path try: - if OldPy: - execfile(path, cfg_globals) - else: - exec(compile(data, path, 'exec'), cfg_globals, None) + exec(compile(data, path, 'exec'), cfg_globals, None) if litConfig.debug: litConfig.note('... loaded config %r' % path) except SystemExit: diff --git a/gnu/llvm/utils/lit/lit/__init__.py b/gnu/llvm/utils/lit/lit/__init__.py index c1bd76b8019..cd84ea4ed6e 100644 --- a/gnu/llvm/utils/lit/lit/__init__.py +++ b/gnu/llvm/utils/lit/lit/__init__.py @@ -1,11 +1,10 @@ """'lit' Testing Tool""" -from __future__ import absolute_import -from .main import main - __author__ = 'Daniel Dunbar' -__email__ = 'daniel@zuster.org' -__versioninfo__ = (0, 5, 0) +__email__ = 'daniel@minormatter.com' +__versioninfo__ = (0, 6, 0) __version__ = '.'.join(str(v) for v in __versioninfo__) + 'dev' __all__ = [] + +from .main import main diff --git a/gnu/llvm/utils/lit/lit/formats/__init__.py b/gnu/llvm/utils/lit/lit/formats/__init__.py index 68627084176..3ff46e93ead 100644 --- a/gnu/llvm/utils/lit/lit/formats/__init__.py +++ b/gnu/llvm/utils/lit/lit/formats/__init__.py @@ -1,4 +1,8 @@ -from __future__ import absolute_import -from lit.formats.base import TestFormat, FileBasedTest, OneCommandPerFileTest -from lit.formats.googletest import GoogleTest -from lit.formats.shtest import ShTest +from lit.formats.base import ( # noqa: F401 + TestFormat, + FileBasedTest, + OneCommandPerFileTest +) + +from lit.formats.googletest import GoogleTest # noqa: F401 +from lit.formats.shtest import ShTest # noqa: F401 diff --git a/gnu/llvm/utils/lit/lit/formats/base.py b/gnu/llvm/utils/lit/lit/formats/base.py index 9e5420ba767..6721d17e334 100644 --- a/gnu/llvm/utils/lit/lit/formats/base.py +++ b/gnu/llvm/utils/lit/lit/formats/base.py @@ -1,6 +1,5 @@ from __future__ import absolute_import import os -import sys import lit.Test import lit.util @@ -81,7 +80,7 @@ class OneCommandPerFileTest(TestFormat): yield test def createTempInput(self, tmp, test): - abstract + raise NotImplementedError('This is an abstract method.') def execute(self, test, litConfig): if test.config.unsupported: diff --git a/gnu/llvm/utils/lit/lit/formats/googletest.py b/gnu/llvm/utils/lit/lit/formats/googletest.py index f0250a3f96d..29a92c4e960 100644 --- a/gnu/llvm/utils/lit/lit/formats/googletest.py +++ b/gnu/llvm/utils/lit/lit/formats/googletest.py @@ -1,5 +1,6 @@ from __future__ import absolute_import import os +import subprocess import sys import lit.Test @@ -34,13 +35,21 @@ class GoogleTest(TestFormat): if kIsWindows: lines = lines.replace('\r', '') lines = lines.split('\n') - except: - litConfig.error("unable to discover google-tests in %r" % path) + except Exception as exc: + out = exc.output if isinstance(exc, subprocess.CalledProcessError) else '' + litConfig.warning("unable to discover google-tests in %r: %s. Process output: %s" + % (path, sys.exc_info()[1], out)) raise StopIteration nested_tests = [] for ln in lines: - if not ln.strip(): + # The test name list includes trailing comments beginning with + # a '#' on some lines, so skip those. We don't support test names + # that use escaping to embed '#' into their name as the names come + # from C++ class and method names where such things are hard and + # uninteresting to support. + ln = ln.split('#', 1)[0].rstrip() + if not ln.lstrip(): continue if 'Running main() from gtest_main.cc' in ln: @@ -49,7 +58,6 @@ class GoogleTest(TestFormat): # handle it here in case upstream googletest is being used. continue - prefix = '' index = 0 while ln[index*2:index*2+2] == ' ': index += 1 @@ -135,4 +143,3 @@ class GoogleTest(TestFormat): return lit.Test.UNRESOLVED, msg return lit.Test.PASS,'' - diff --git a/gnu/llvm/utils/lit/lit/main.py b/gnu/llvm/utils/lit/lit/main.py index 50927e2cbf0..ac3066eea72 100755 --- a/gnu/llvm/utils/lit/lit/main.py +++ b/gnu/llvm/utils/lit/lit/main.py @@ -7,7 +7,15 @@ See lit.pod for more information. """ from __future__ import absolute_import -import math, os, platform, random, re, sys, time +import os +import platform +import random +import re +import sys +import time +import argparse +import tempfile +import shutil import lit.ProgressBar import lit.LitConfig @@ -20,7 +28,6 @@ class TestingProgressDisplay(object): def __init__(self, opts, numTests, progressBar=None): self.opts = opts self.numTests = numTests - self.current = None self.progressBar = progressBar self.completed = 0 @@ -132,124 +139,146 @@ def sort_by_incremental_cache(run): run.tests.sort(key = lambda t: sortIndex(t)) def main(builtinParameters = {}): - # Use processes by default on Unix platforms. - isWindows = platform.system() == 'Windows' - useProcessesIsDefault = not isWindows + # Create a temp directory inside the normal temp directory so that we can + # try to avoid temporary test file leaks. The user can avoid this behavior + # by setting LIT_PRESERVES_TMP in the environment, so they can easily use + # their own temp directory to monitor temporary file leaks or handle them at + # the buildbot level. + lit_tmp = None + if 'LIT_PRESERVES_TMP' not in os.environ: + lit_tmp = tempfile.mkdtemp(prefix="lit_tmp_") + os.environ.update({ + 'TMPDIR': lit_tmp, + 'TMP': lit_tmp, + 'TEMP': lit_tmp, + 'TEMPDIR': lit_tmp, + }) + # FIXME: If Python does not exit cleanly, this directory will not be cleaned + # up. We should consider writing the lit pid into the temp directory, + # scanning for stale temp directories, and deleting temp directories whose + # lit process has died. + try: + main_with_tmp(builtinParameters) + finally: + if lit_tmp: + shutil.rmtree(lit_tmp) - global options - from optparse import OptionParser, OptionGroup - parser = OptionParser("usage: %prog [options] {file-or-path}") +def main_with_tmp(builtinParameters): + parser = argparse.ArgumentParser() + parser.add_argument('test_paths', + nargs='*', + help='Files or paths to include in the test suite') - parser.add_option("", "--version", dest="show_version", + parser.add_argument("--version", dest="show_version", help="Show version and exit", action="store_true", default=False) - parser.add_option("-j", "--threads", dest="numThreads", metavar="N", + parser.add_argument("-j", "--threads", dest="numThreads", metavar="N", help="Number of testing threads", - type=int, action="store", default=None) - parser.add_option("", "--config-prefix", dest="configPrefix", + type=int, default=None) + parser.add_argument("--config-prefix", dest="configPrefix", metavar="NAME", help="Prefix for 'lit' config files", action="store", default=None) - parser.add_option("-D", "--param", dest="userParameters", + parser.add_argument("-D", "--param", dest="userParameters", metavar="NAME=VAL", help="Add 'NAME' = 'VAL' to the user defined parameters", type=str, action="append", default=[]) - group = OptionGroup(parser, "Output Format") + format_group = parser.add_argument_group("Output Format") # FIXME: I find these names very confusing, although I like the # functionality. - group.add_option("-q", "--quiet", dest="quiet", + format_group.add_argument("-q", "--quiet", help="Suppress no error output", action="store_true", default=False) - group.add_option("-s", "--succinct", dest="succinct", + format_group.add_argument("-s", "--succinct", help="Reduce amount of output", action="store_true", default=False) - group.add_option("-v", "--verbose", dest="showOutput", + format_group.add_argument("-v", "--verbose", dest="showOutput", help="Show test output for failures", action="store_true", default=False) - group.add_option("-a", "--show-all", dest="showAllOutput", + format_group.add_argument("-a", "--show-all", dest="showAllOutput", help="Display all commandlines and output", action="store_true", default=False) - group.add_option("-o", "--output", dest="output_path", + format_group.add_argument("-o", "--output", dest="output_path", help="Write test results to the provided path", - action="store", type=str, metavar="PATH") - group.add_option("", "--no-progress-bar", dest="useProgressBar", + action="store", metavar="PATH") + format_group.add_argument("--no-progress-bar", dest="useProgressBar", help="Do not use curses based progress bar", action="store_false", default=True) - group.add_option("", "--show-unsupported", dest="show_unsupported", + format_group.add_argument("--show-unsupported", help="Show unsupported tests", action="store_true", default=False) - group.add_option("", "--show-xfail", dest="show_xfail", + format_group.add_argument("--show-xfail", help="Show tests that were expected to fail", action="store_true", default=False) - parser.add_option_group(group) - group = OptionGroup(parser, "Test Execution") - group.add_option("", "--path", dest="path", + execution_group = parser.add_argument_group("Test Execution") + execution_group.add_argument("--path", help="Additional paths to add to testing environment", action="append", type=str, default=[]) - group.add_option("", "--vg", dest="useValgrind", + execution_group.add_argument("--vg", dest="useValgrind", help="Run tests under valgrind", action="store_true", default=False) - group.add_option("", "--vg-leak", dest="valgrindLeakCheck", + execution_group.add_argument("--vg-leak", dest="valgrindLeakCheck", help="Check for memory leaks under valgrind", action="store_true", default=False) - group.add_option("", "--vg-arg", dest="valgrindArgs", metavar="ARG", + execution_group.add_argument("--vg-arg", dest="valgrindArgs", metavar="ARG", help="Specify an extra argument for valgrind", type=str, action="append", default=[]) - group.add_option("", "--time-tests", dest="timeTests", + execution_group.add_argument("--time-tests", dest="timeTests", help="Track elapsed wall time for each test", action="store_true", default=False) - group.add_option("", "--no-execute", dest="noExecute", + execution_group.add_argument("--no-execute", dest="noExecute", help="Don't execute any tests (assume PASS)", action="store_true", default=False) - group.add_option("", "--xunit-xml-output", dest="xunit_output_file", + execution_group.add_argument("--xunit-xml-output", dest="xunit_output_file", help=("Write XUnit-compatible XML test reports to the" " specified file"), default=None) - group.add_option("", "--timeout", dest="maxIndividualTestTime", + execution_group.add_argument("--timeout", dest="maxIndividualTestTime", help="Maximum time to spend running a single test (in seconds)." "0 means no time limit. [Default: 0]", type=int, default=None) - parser.add_option_group(group) + execution_group.add_argument("--max-failures", dest="maxFailures", + help="Stop execution after the given number of failures.", + action="store", type=int, default=None) - group = OptionGroup(parser, "Test Selection") - group.add_option("", "--max-tests", dest="maxTests", metavar="N", + selection_group = parser.add_argument_group("Test Selection") + selection_group.add_argument("--max-tests", dest="maxTests", metavar="N", help="Maximum number of tests to run", action="store", type=int, default=None) - group.add_option("", "--max-time", dest="maxTime", metavar="N", + selection_group.add_argument("--max-time", dest="maxTime", metavar="N", help="Maximum time to spend testing (in seconds)", action="store", type=float, default=None) - group.add_option("", "--shuffle", dest="shuffle", + selection_group.add_argument("--shuffle", help="Run tests in random order", action="store_true", default=False) - group.add_option("-i", "--incremental", dest="incremental", + selection_group.add_argument("-i", "--incremental", help="Run modified and failing tests first (updates " "mtimes)", action="store_true", default=False) - group.add_option("", "--filter", dest="filter", metavar="REGEX", + selection_group.add_argument("--filter", metavar="REGEX", help=("Only run tests with paths matching the given " "regular expression"), action="store", default=None) - parser.add_option_group(group) - group = OptionGroup(parser, "Debug and Experimental Options") - group.add_option("", "--debug", dest="debug", + debug_group = parser.add_argument_group("Debug and Experimental Options") + debug_group.add_argument("--debug", help="Enable debugging (for 'lit' development)", action="store_true", default=False) - group.add_option("", "--show-suites", dest="showSuites", + debug_group.add_argument("--show-suites", dest="showSuites", help="Show discovered test suites", action="store_true", default=False) - group.add_option("", "--show-tests", dest="showTests", + debug_group.add_argument("--show-tests", dest="showTests", help="Show all discovered tests", action="store_true", default=False) - group.add_option("", "--use-processes", dest="useProcesses", + debug_group.add_argument("--use-processes", dest="useProcesses", help="Run tests in parallel with processes (not threads)", - action="store_true", default=useProcessesIsDefault) - group.add_option("", "--use-threads", dest="useProcesses", + action="store_true", default=True) + debug_group.add_argument("--use-threads", dest="useProcesses", help="Run tests in parallel with threads (not processes)", - action="store_false", default=useProcessesIsDefault) - parser.add_option_group(group) + action="store_false", default=True) - (opts, args) = parser.parse_args() + opts = parser.parse_args() + args = opts.test_paths if opts.show_version: print("lit %s" % (lit.__version__,)) @@ -259,14 +288,10 @@ def main(builtinParameters = {}): parser.error('No inputs specified') if opts.numThreads is None: -# Python <2.5 has a race condition causing lit to always fail with numThreads>1 -# http://bugs.python.org/issue1731717 -# I haven't seen this bug occur with 2.5.2 and later, so only enable multiple -# threads by default there. - if sys.hexversion >= 0x2050200: - opts.numThreads = lit.util.detectCPUs() - else: - opts.numThreads = 1 + opts.numThreads = lit.util.detectCPUs() + + if opts.maxFailures == 0: + parser.error("Setting --max-failures to 0 does not have any effect.") inputs = args @@ -280,12 +305,13 @@ def main(builtinParameters = {}): userParams[name] = val # Decide what the requested maximum indvidual test time should be - if opts.maxIndividualTestTime != None: + if opts.maxIndividualTestTime is not None: maxIndividualTestTime = opts.maxIndividualTestTime else: # Default is zero maxIndividualTestTime = 0 + isWindows = platform.system() == 'Windows' # Create the global config object. litConfig = lit.LitConfig.LitConfig( @@ -300,7 +326,8 @@ def main(builtinParameters = {}): isWindows = isWindows, params = userParams, config_prefix = opts.configPrefix, - maxIndividualTestTime = maxIndividualTestTime) + maxIndividualTestTime = maxIndividualTestTime, + maxFailures = opts.maxFailures) # Perform test discovery. run = lit.run.Run(litConfig, @@ -309,7 +336,7 @@ def main(builtinParameters = {}): # After test discovery the configuration might have changed # the maxIndividualTestTime. If we explicitly set this on the # command line then override what was set in the test configuration - if opts.maxIndividualTestTime != None: + if opts.maxIndividualTestTime is not None: if opts.maxIndividualTestTime != litConfig.maxIndividualTestTime: litConfig.note(('The test suite configuration requested an individual' ' test timeout of {0} seconds but a timeout of {1} seconds was' @@ -453,7 +480,8 @@ def main(builtinParameters = {}): ('Expected Failing Tests', lit.Test.XFAIL), ('Timed Out Tests', lit.Test.TIMEOUT)): if (lit.Test.XFAIL == code and not opts.show_xfail) or \ - (lit.Test.UNSUPPORTED == code and not opts.show_unsupported): + (lit.Test.UNSUPPORTED == code and not opts.show_unsupported) or \ + (lit.Test.UNRESOLVED == code and (opts.maxFailures is not None)): continue elts = byCode.get(code) if not elts: diff --git a/gnu/llvm/utils/lit/lit/run.py b/gnu/llvm/utils/lit/lit/run.py index bbf644ef7db..f7e84d316a7 100644 --- a/gnu/llvm/utils/lit/lit/run.py +++ b/gnu/llvm/utils/lit/lit/run.py @@ -152,6 +152,21 @@ def run_one_tester(run, provider, display): ### +class _Display(object): + def __init__(self, display, provider, maxFailures): + self.display = display + self.provider = provider + self.maxFailures = maxFailures or object() + self.failedCount = 0 + def update(self, test): + self.display.update(test) + self.failedCount += (test.result.code == lit.Test.FAIL) + if self.failedCount == self.maxFailures: + self.provider.cancel() + +def handleFailures(provider, consumer, maxFailures): + consumer.display = _Display(consumer.display, provider, maxFailures) + class Run(object): """ This class represents a concrete, configured testing run. @@ -232,6 +247,7 @@ class Run(object): # Create the test provider. provider = TestProvider(queue_impl, canceled_flag) + handleFailures(provider, consumer, self.lit_config.maxFailures) # Queue the tests outside the main thread because we can't guarantee # that we can put() all the tests without blocking: diff --git a/gnu/llvm/utils/lit/lit/util.py b/gnu/llvm/utils/lit/lit/util.py index 40a57716869..be37998c6f1 100644 --- a/gnu/llvm/utils/lit/lit/util.py +++ b/gnu/llvm/utils/lit/lit/util.py @@ -20,6 +20,8 @@ def to_string(bytes): def convert_string(bytes): try: return to_string(bytes.decode('utf-8')) + except AttributeError: # 'str' object has no attribute 'decode'. + return str(bytes) except UnicodeError: return str(bytes) @@ -65,11 +67,18 @@ def mkdir_p(path): def capture(args, env=None): """capture(command) - Run the given command (or argv list) in a shell and - return the standard output.""" + return the standard output. Raises a CalledProcessError if the command + exits with a non-zero status.""" p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) - out,_ = p.communicate() - return convert_string(out) + out, err = p.communicate() + out = convert_string(out) + err = convert_string(err) + if p.returncode != 0: + raise subprocess.CalledProcessError(cmd=args, + returncode=p.returncode, + output="{}\n{}".format(out, err)) + return out def which(command, paths = None): """which(command, [paths]) - Look up the given command in the paths string @@ -105,8 +114,8 @@ def which(command, paths = None): def checkToolsPath(dir, tools): for tool in tools: if not os.path.exists(os.path.join(dir, tool)): - return False; - return True; + return False + return True def whichTools(tools, paths): for path in paths.split(os.pathsep): @@ -242,7 +251,7 @@ def usePlatformSdkOnDarwin(config, lit_config): # default system root path. if 'darwin' in config.target_triple: try: - cmd = subprocess.Popen(['xcrun', '--show-sdk-path'], + cmd = subprocess.Popen(['xcrun', '--show-sdk-path', '--sdk', 'macosx'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = cmd.communicate() out = out.strip() diff --git a/gnu/llvm/utils/lit/tests/Inputs/shtest-timeout/infinite_loop.py b/gnu/llvm/utils/lit/tests/Inputs/shtest-timeout/infinite_loop.py index 55720479d33..c8ced24f29c 100644 --- a/gnu/llvm/utils/lit/tests/Inputs/shtest-timeout/infinite_loop.py +++ b/gnu/llvm/utils/lit/tests/Inputs/shtest-timeout/infinite_loop.py @@ -1,7 +1,6 @@ # RUN: %{python} %s from __future__ import print_function -import time import sys print("Running infinite loop") diff --git a/gnu/llvm/utils/lit/tests/Inputs/shtest-timeout/short.py b/gnu/llvm/utils/lit/tests/Inputs/shtest-timeout/short.py index 424b7092d83..8963db59f51 100644 --- a/gnu/llvm/utils/lit/tests/Inputs/shtest-timeout/short.py +++ b/gnu/llvm/utils/lit/tests/Inputs/shtest-timeout/short.py @@ -1,6 +1,4 @@ # RUN: %{python} %s from __future__ import print_function -import sys - print("short program") diff --git a/gnu/llvm/utils/lit/tests/Inputs/testrunner-custom-parsers/lit.cfg b/gnu/llvm/utils/lit/tests/Inputs/testrunner-custom-parsers/lit.cfg new file mode 100644 index 00000000000..cf46c1674e5 --- /dev/null +++ b/gnu/llvm/utils/lit/tests/Inputs/testrunner-custom-parsers/lit.cfg @@ -0,0 +1,14 @@ +import lit.formats +import os +import lit.Test + +class TestParserFormat(lit.formats.FileBasedTest): + def execute(self, test, lit_config): + return lit.Test.PASS, '' + +config.name = 'custom-parsers' +config.suffixes = ['.txt'] +config.test_format = TestParserFormat() +config.test_source_root = None +config.test_exec_root = None +config.target_triple = 'x86_64-unknown-unknown' diff --git a/gnu/llvm/utils/lit/tests/Inputs/testrunner-custom-parsers/test.txt b/gnu/llvm/utils/lit/tests/Inputs/testrunner-custom-parsers/test.txt new file mode 100644 index 00000000000..ed118f382fe --- /dev/null +++ b/gnu/llvm/utils/lit/tests/Inputs/testrunner-custom-parsers/test.txt @@ -0,0 +1,13 @@ + +// MY_TAG. +// foo bar baz +// MY_RUN: baz +// MY_LIST: one, two +// MY_LIST: three, four +// MY_RUN: foo \ +// MY_RUN: bar +// +// MY_CUSTOM: a b c +// +// END. +// MY_LIST: five diff --git a/gnu/llvm/utils/lit/tests/max-failures.py b/gnu/llvm/utils/lit/tests/max-failures.py new file mode 100644 index 00000000000..5cc258dd08a --- /dev/null +++ b/gnu/llvm/utils/lit/tests/max-failures.py @@ -0,0 +1,14 @@ +# Check the behavior of --max-failures option. +# +# RUN: not %{lit} -j 1 -v %{inputs}/shtest-shell > %t.out +# RUN: not %{lit} --max-failures=1 -j 1 -v %{inputs}/shtest-shell >> %t.out +# RUN: not %{lit} --max-failures=2 -j 1 -v %{inputs}/shtest-shell >> %t.out +# RUN: not %{lit} --max-failures=0 -j 1 -v %{inputs}/shtest-shell 2>> %t.out +# RUN: FileCheck < %t.out %s +# +# END. + +# CHECK: Failing Tests (3) +# CHECK: Failing Tests (1) +# CHECK: Failing Tests (2) +# CHECK: error: Setting --max-failures to 0 does not have any effect. diff --git a/gnu/llvm/utils/lit/tests/shtest-timeout.py b/gnu/llvm/utils/lit/tests/shtest-timeout.py index e6b2947a4f7..87f431de250 100644 --- a/gnu/llvm/utils/lit/tests/shtest-timeout.py +++ b/gnu/llvm/utils/lit/tests/shtest-timeout.py @@ -22,27 +22,26 @@ # RUN: FileCheck --check-prefix=CHECK-OUT-COMMON < %t.intsh.out %s # RUN: FileCheck --check-prefix=CHECK-INTSH-OUT < %t.intsh.out %s # RUN: FileCheck --check-prefix=CHECK-INTSH-ERR < %t.intsh.err %s -# + # CHECK-INTSH-OUT: TIMEOUT: per_test_timeout :: infinite_loop.py -# CHECK-INTSH-OUT: Command 0 Reached Timeout: True -# CHECK-INTSH-OUT: Command 0 Output: +# CHECK-INTSH-OUT: command output: # CHECK-INTSH-OUT-NEXT: Running infinite loop - +# CHECK-INTSH-OUT: command reached timeout: True # CHECK-INTSH-OUT: TIMEOUT: per_test_timeout :: quick_then_slow.py # CHECK-INTSH-OUT: Timeout: Reached timeout of 1 seconds # CHECK-INTSH-OUT: Command Output -# CHECK-INTSH-OUT: Command 0 Reached Timeout: False -# CHECK-INTSH-OUT: Command 0 Output: +# CHECK-INTSH-OUT: command output: # CHECK-INTSH-OUT-NEXT: Running in quick mode -# CHECK-INTSH-OUT: Command 1 Reached Timeout: True -# CHECK-INTSH-OUT: Command 1 Output: +# CHECK-INTSH-OUT: command reached timeout: False +# CHECK-INTSH-OUT: command output: # CHECK-INTSH-OUT-NEXT: Running in slow mode +# CHECK-INTSH-OUT: command reached timeout: True # CHECK-INTSH-OUT: TIMEOUT: per_test_timeout :: slow.py -# CHECK-INTSH-OUT: Command 0 Reached Timeout: True -# CHECK-INTSH-OUT: Command 0 Output: +# CHECK-INTSH-OUT: command output: # CHECK-INTSH-OUT-NEXT: Running slow program +# CHECK-INTSH-OUT: command reached timeout: True # CHECK-INTSH-ERR: Using internal shell diff --git a/gnu/llvm/utils/lit/tests/unit/ShUtil.py b/gnu/llvm/utils/lit/tests/unit/ShUtil.py new file mode 100644 index 00000000000..9cf42dbbcef --- /dev/null +++ b/gnu/llvm/utils/lit/tests/unit/ShUtil.py @@ -0,0 +1,112 @@ +# RUN: %{python} %s + +import unittest + +from lit.ShUtil import Command, Pipeline, Seq, ShLexer, ShParser + + +class TestShLexer(unittest.TestCase): + def lex(self, str, *args, **kwargs): + return list(ShLexer(str, *args, **kwargs).lex()) + + def test_basic(self): + self.assertEqual(self.lex('a|b>c&d<e;f'), + ['a', ('|',), 'b', ('>',), 'c', ('&',), 'd', + ('<',), 'e', (';',), 'f']) + + def test_redirection_tokens(self): + self.assertEqual(self.lex('a2>c'), + ['a2', ('>',), 'c']) + self.assertEqual(self.lex('a 2>c'), + ['a', ('>',2), 'c']) + + def test_quoting(self): + self.assertEqual(self.lex(""" 'a' """), + ['a']) + self.assertEqual(self.lex(""" "hello\\"world" """), + ['hello"world']) + self.assertEqual(self.lex(""" "hello\\'world" """), + ["hello\\'world"]) + self.assertEqual(self.lex(""" "hello\\\\world" """), + ["hello\\world"]) + self.assertEqual(self.lex(""" he"llo wo"rld """), + ["hello world"]) + self.assertEqual(self.lex(""" a\\ b a\\\\b """), + ["a b", "a\\b"]) + self.assertEqual(self.lex(""" "" "" """), + ["", ""]) + self.assertEqual(self.lex(""" a\\ b """, win32Escapes = True), + ['a\\', 'b']) + +class TestShParse(unittest.TestCase): + def parse(self, str): + return ShParser(str).parse() + + def test_basic(self): + self.assertEqual(self.parse('echo hello'), + Pipeline([Command(['echo', 'hello'], [])], False)) + self.assertEqual(self.parse('echo ""'), + Pipeline([Command(['echo', ''], [])], False)) + self.assertEqual(self.parse("""echo -DFOO='a'"""), + Pipeline([Command(['echo', '-DFOO=a'], [])], False)) + self.assertEqual(self.parse('echo -DFOO="a"'), + Pipeline([Command(['echo', '-DFOO=a'], [])], False)) + + def test_redirection(self): + self.assertEqual(self.parse('echo hello > c'), + Pipeline([Command(['echo', 'hello'], + [((('>'),), 'c')])], False)) + self.assertEqual(self.parse('echo hello > c >> d'), + Pipeline([Command(['echo', 'hello'], [(('>',), 'c'), + (('>>',), 'd')])], False)) + self.assertEqual(self.parse('a 2>&1'), + Pipeline([Command(['a'], [(('>&',2), '1')])], False)) + + def test_pipeline(self): + self.assertEqual(self.parse('a | b'), + Pipeline([Command(['a'], []), + Command(['b'], [])], + False)) + + self.assertEqual(self.parse('a | b | c'), + Pipeline([Command(['a'], []), + Command(['b'], []), + Command(['c'], [])], + False)) + + def test_list(self): + self.assertEqual(self.parse('a ; b'), + Seq(Pipeline([Command(['a'], [])], False), + ';', + Pipeline([Command(['b'], [])], False))) + + self.assertEqual(self.parse('a & b'), + Seq(Pipeline([Command(['a'], [])], False), + '&', + Pipeline([Command(['b'], [])], False))) + + self.assertEqual(self.parse('a && b'), + Seq(Pipeline([Command(['a'], [])], False), + '&&', + Pipeline([Command(['b'], [])], False))) + + self.assertEqual(self.parse('a || b'), + Seq(Pipeline([Command(['a'], [])], False), + '||', + Pipeline([Command(['b'], [])], False))) + + self.assertEqual(self.parse('a && b || c'), + Seq(Seq(Pipeline([Command(['a'], [])], False), + '&&', + Pipeline([Command(['b'], [])], False)), + '||', + Pipeline([Command(['c'], [])], False))) + + self.assertEqual(self.parse('a; b'), + Seq(Pipeline([Command(['a'], [])], False), + ';', + Pipeline([Command(['b'], [])], False))) + +if __name__ == '__main__': + unittest.main() + diff --git a/gnu/llvm/utils/lit/tests/unit/TestRunner.py b/gnu/llvm/utils/lit/tests/unit/TestRunner.py new file mode 100644 index 00000000000..ff11834fed7 --- /dev/null +++ b/gnu/llvm/utils/lit/tests/unit/TestRunner.py @@ -0,0 +1,114 @@ +# RUN: %{python} %s +# +# END. + + +import unittest +import platform +import os.path +import tempfile + +import lit +from lit.TestRunner import ParserKind, IntegratedTestKeywordParser, \ + parseIntegratedTestScript + + +class TestIntegratedTestKeywordParser(unittest.TestCase): + inputTestCase = None + + @staticmethod + def load_keyword_parser_lit_tests(): + """ + Create and load the LIT test suite and test objects used by + TestIntegratedTestKeywordParser + """ + # Create the global config object. + lit_config = lit.LitConfig.LitConfig(progname='lit', + path=[], + quiet=False, + useValgrind=False, + valgrindLeakCheck=False, + valgrindArgs=[], + noExecute=False, + debug=False, + isWindows=( + platform.system() == 'Windows'), + params={}) + TestIntegratedTestKeywordParser.litConfig = lit_config + # Perform test discovery. + test_path = os.path.dirname(os.path.dirname(__file__)) + inputs = [os.path.join(test_path, 'Inputs/testrunner-custom-parsers/')] + assert os.path.isdir(inputs[0]) + run = lit.run.Run(lit_config, + lit.discovery.find_tests_for_inputs(lit_config, inputs)) + assert len(run.tests) == 1 and "there should only be one test" + TestIntegratedTestKeywordParser.inputTestCase = run.tests[0] + + @staticmethod + def make_parsers(): + def custom_parse(line_number, line, output): + if output is None: + output = [] + output += [part for part in line.split(' ') if part.strip()] + return output + + return [ + IntegratedTestKeywordParser("MY_TAG.", ParserKind.TAG), + IntegratedTestKeywordParser("MY_DNE_TAG.", ParserKind.TAG), + IntegratedTestKeywordParser("MY_LIST:", ParserKind.LIST), + IntegratedTestKeywordParser("MY_RUN:", ParserKind.COMMAND), + IntegratedTestKeywordParser("MY_CUSTOM:", ParserKind.CUSTOM, + custom_parse) + ] + + @staticmethod + def get_parser(parser_list, keyword): + for p in parser_list: + if p.keyword == keyword: + return p + assert False and "parser not found" + + @staticmethod + def parse_test(parser_list): + script = parseIntegratedTestScript( + TestIntegratedTestKeywordParser.inputTestCase, + additional_parsers=parser_list, require_script=False) + assert not isinstance(script, lit.Test.Result) + assert isinstance(script, list) + assert len(script) == 0 + + def test_tags(self): + parsers = self.make_parsers() + self.parse_test(parsers) + tag_parser = self.get_parser(parsers, 'MY_TAG.') + dne_tag_parser = self.get_parser(parsers, 'MY_DNE_TAG.') + self.assertTrue(tag_parser.getValue()) + self.assertFalse(dne_tag_parser.getValue()) + + def test_lists(self): + parsers = self.make_parsers() + self.parse_test(parsers) + list_parser = self.get_parser(parsers, 'MY_LIST:') + self.assertItemsEqual(list_parser.getValue(), + ['one', 'two', 'three', 'four']) + + def test_commands(self): + parsers = self.make_parsers() + self.parse_test(parsers) + cmd_parser = self.get_parser(parsers, 'MY_RUN:') + value = cmd_parser.getValue() + self.assertEqual(len(value), 2) # there are only two run lines + self.assertEqual(value[0].strip(), 'baz') + self.assertEqual(value[1].strip(), 'foo bar') + + def test_custom(self): + parsers = self.make_parsers() + self.parse_test(parsers) + custom_parser = self.get_parser(parsers, 'MY_CUSTOM:') + value = custom_parser.getValue() + self.assertItemsEqual(value, ['a', 'b', 'c']) + + +if __name__ == '__main__': + TestIntegratedTestKeywordParser.load_keyword_parser_lit_tests() + unittest.main(verbosity=2) diff --git a/gnu/llvm/utils/lit/tests/usage.py b/gnu/llvm/utils/lit/tests/usage.py index e10d6134a03..d168c5eff9e 100644 --- a/gnu/llvm/utils/lit/tests/usage.py +++ b/gnu/llvm/utils/lit/tests/usage.py @@ -3,4 +3,4 @@ # RUN: %{lit} --help > %t.out # RUN: FileCheck < %t.out %s # -# CHECK: Usage: lit.py [options] {file-or-path} +# CHECK: usage: lit.py [-h] diff --git a/gnu/llvm/utils/llvm-lit/llvm-lit.in b/gnu/llvm/utils/llvm-lit/llvm-lit.in index fc962021d73..57924fab8d3 100755 --- a/gnu/llvm/utils/llvm-lit/llvm-lit.in +++ b/gnu/llvm/utils/llvm-lit/llvm-lit.in @@ -40,5 +40,5 @@ if os.path.exists(compilerrt_obj_root): os.path.join(compilerrt_obj_root, 'test') if __name__=='__main__': - import lit - lit.main(builtin_parameters) + from lit.main import main + main(builtin_parameters) diff --git a/gnu/llvm/utils/not/not.cpp b/gnu/llvm/utils/not/not.cpp index 23062fb323d..271fbcfe94a 100644 --- a/gnu/llvm/utils/not/not.cpp +++ b/gnu/llvm/utils/not/not.cpp @@ -12,7 +12,6 @@ // not --crash cmd // Will return true if cmd crashes (e.g. for testing crash reporting). -#include "llvm/Support/Path.h" #include "llvm/Support/Program.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; diff --git a/gnu/llvm/utils/opt-viewer/opt-viewer.py b/gnu/llvm/utils/opt-viewer/opt-viewer.py new file mode 100755 index 00000000000..c936597475c --- /dev/null +++ b/gnu/llvm/utils/opt-viewer/opt-viewer.py @@ -0,0 +1,318 @@ +#!/usr/bin/env python2.7 + +from __future__ import print_function + +desc = '''Generate HTML output to visualize optimization records from the YAML files +generated with -fsave-optimization-record and -fdiagnostics-show-hotness. + +The tools requires PyYAML and Pygments Python packages. + +For faster parsing, you may want to use libYAML with PyYAML.''' + +import yaml +# Try to use the C parser. +try: + from yaml import CLoader as Loader +except ImportError: + from yaml import Loader +import argparse +import os.path +import re +import subprocess +import shutil +from pygments import highlight +from pygments.lexers.c_cpp import CppLexer +from pygments.formatters import HtmlFormatter + +parser = argparse.ArgumentParser(description=desc) +parser.add_argument('yaml_files', nargs='+') +parser.add_argument('output_dir') +parser.add_argument('-source-dir', '-s', default='', help='set source directory') +args = parser.parse_args() + +p = subprocess.Popen(['c++filt', '-n'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) + + +def demangle(name): + p.stdin.write(name + '\n') + return p.stdout.readline().rstrip() + + +class Remark(yaml.YAMLObject): + max_hotness = 0 + + # Work-around for http://pyyaml.org/ticket/154. + yaml_loader = Loader + + @classmethod + def should_display_hotness(cls): + # If max_hotness is 0 at the end, we assume hotness information is + # missing and no relative hotness information is displayed + return cls.max_hotness != 0 + + # Map function names to their source location for function where inlining happened + caller_loc = dict() + + def __getattr__(self, name): + # If hotness is missing, assume 0 + if name == 'Hotness': + return 0 + raise AttributeError + + @property + def File(self): + return self.DebugLoc['File'] + + @property + def Line(self): + return int(self.DebugLoc['Line']) + + @property + def Column(self): + return self.DebugLoc['Column'] + + @property + def DebugLocString(self): + return "{}:{}:{}".format(self.File, self.Line, self.Column) + + @property + def DemangledFunctionName(self): + return demangle(self.Function) + + @classmethod + def make_link(cls, File, Line): + return "{}#L{}".format(SourceFileRenderer.html_file_name(File), Line) + + @property + def Link(self): + return Remark.make_link(self.File, self.Line) + + def getArgString(self, mapping): + mapping = mapping.copy() + dl = mapping.get('DebugLoc') + if dl: + del mapping['DebugLoc'] + + assert(len(mapping) == 1) + (key, value) = mapping.items()[0] + + if key == 'Caller' or key == 'Callee': + value = demangle(value) + + if dl and key != 'Caller': + return "<a href={}>{}</a>".format( + Remark.make_link(dl['File'], dl['Line']), value) + else: + return value + + @property + def message(self): + # Args is a list of mappings (dictionaries) + values = [self.getArgString(mapping) for mapping in self.Args] + return "".join(values) + + @property + def RelativeHotness(self): + if Remark.should_display_hotness(): + return "{}%".format(int(round(self.Hotness * 100 / Remark.max_hotness))) + else: + return '' + + @property + def key(self): + return (self.__class__, self.Pass, self.Name, self.File, self.Line, self.Column, self.message) + + +class Analysis(Remark): + yaml_tag = '!Analysis' + + @property + def color(self): + return "white" + + +class AnalysisFPCommute(Analysis): + yaml_tag = '!AnalysisFPCommute' + + +class AnalysisAliasing(Analysis): + yaml_tag = '!AnalysisAliasing' + + +class Passed(Remark): + yaml_tag = '!Passed' + + @property + def color(self): + return "green" + + +class Missed(Remark): + yaml_tag = '!Missed' + + @property + def color(self): + return "red" + + +class SourceFileRenderer: + def __init__(self, filename): + existing_filename = None + if os.path.exists(filename): + existing_filename = filename + else: + fn = os.path.join(args.source_dir, filename) + if os.path.exists(fn): + existing_filename = fn + + self.stream = open(os.path.join(args.output_dir, SourceFileRenderer.html_file_name(filename)), 'w') + if existing_filename: + self.source_stream = open(existing_filename) + else: + self.source_stream = None + print(''' +<html> +<h1>Unable to locate file {}</h1> +</html> + '''.format(filename), file=self.stream) + + self.html_formatter = HtmlFormatter() + self.cpp_lexer = CppLexer() + + def render_source_line(self, linenum, line): + html_line = highlight(line, self.cpp_lexer, self.html_formatter) + print(''' +<tr> +<td><a name=\"L{linenum}\">{linenum}</a></td> +<td></td> +<td></td> +<td>{html_line}</td> +</tr>'''.format(**locals()), file=self.stream) + + def render_inline_remarks(self, r, line): + inlining_context = r.DemangledFunctionName + dl = Remark.caller_loc.get(r.Function) + if dl: + link = Remark.make_link(dl['File'], dl['Line'] - 2) + inlining_context = "<a href={link}>{r.DemangledFunctionName}</a>".format(**locals()) + + # Column is the number of characters *including* tabs, keep those and + # replace everything else with spaces. + indent = line[:r.Column - 1] + indent = re.sub('\S', ' ', indent) + print(''' +<tr> +<td></td> +<td>{r.RelativeHotness}</td> +<td class=\"column-entry-{r.color}\">{r.Pass}</td> +<td><pre style="display:inline">{indent}</pre><span class=\"column-entry-yellow\"> {r.message} </span></td> +<td class=\"column-entry-yellow\">{inlining_context}</td> +</tr>'''.format(**locals()), file=self.stream) + + def render(self, line_remarks): + if not self.source_stream: + return + + print(''' +<html> +<head> +<link rel='stylesheet' type='text/css' href='style.css'> +</head> +<body> +<div class="centered"> +<table> +<tr> +<td>Line</td> +<td>Hotness</td> +<td>Optimization</td> +<td>Source</td> +<td>Inline Context</td> +</tr>''', file=self.stream) + for (linenum, line) in enumerate(self.source_stream.readlines(), start=1): + self.render_source_line(linenum, line) + for remark in line_remarks.get(linenum, []): + self.render_inline_remarks(remark, line) + print(''' +</table> +</body> +</html>''', file=self.stream) + + @classmethod + def html_file_name(cls, filename): + return filename.replace('/', '_') + ".html" + + +class IndexRenderer: + def __init__(self): + self.stream = open(os.path.join(args.output_dir, 'index.html'), 'w') + + def render_entry(self, r): + print(''' +<tr> +<td><a href={r.Link}>{r.DebugLocString}</a></td> +<td>{r.RelativeHotness}</td> +<td>{r.DemangledFunctionName}</td> +<td class=\"column-entry-{r.color}\">{r.Pass}</td> +</tr>'''.format(**locals()), file=self.stream) + + def render(self, all_remarks): + print(''' +<html> +<head> +<link rel='stylesheet' type='text/css' href='style.css'> +</head> +<body> +<div class="centered"> +<table> +<tr> +<td>Source Location</td> +<td>Hotness</td> +<td>Function</td> +<td>Pass</td> +</tr>''', file=self.stream) + for remark in all_remarks: + self.render_entry(remark) + print(''' +</table> +</body> +</html>''', file=self.stream) + + +all_remarks = dict() +file_remarks = dict() + +for input_file in args.yaml_files: + f = open(input_file) + docs = yaml.load_all(f, Loader=Loader) + for remark in docs: + # Avoid remarks withoug debug location or if they are duplicated + if not hasattr(remark, 'DebugLoc') or remark.key in all_remarks: + continue + all_remarks[remark.key] = remark + + file_remarks.setdefault(remark.File, dict()).setdefault(remark.Line, []).append(remark) + + Remark.max_hotness = max(Remark.max_hotness, remark.Hotness) + +# Set up a map between function names and their source location for function where inlining happened +for remark in all_remarks.itervalues(): + if type(remark) == Passed and remark.Pass == "inline" and remark.Name == "Inlined": + for arg in remark.Args: + caller = arg.get('Caller') + if caller: + Remark.caller_loc[caller] = arg['DebugLoc'] + +if Remark.should_display_hotness(): + sorted_remarks = sorted(all_remarks.itervalues(), key=lambda r: r.Hotness, reverse=True) +else: + sorted_remarks = sorted(all_remarks.itervalues(), key=lambda r: (r.File, r.Line, r.Column)) + +if not os.path.exists(args.output_dir): + os.mkdir(args.output_dir) + +for (filename, remarks) in file_remarks.iteritems(): + SourceFileRenderer(filename).render(remarks) + +IndexRenderer().render(sorted_remarks) + +shutil.copy(os.path.join(os.path.dirname(os.path.realpath(__file__)), "style.css"), args.output_dir) diff --git a/gnu/llvm/utils/opt-viewer/style.css b/gnu/llvm/utils/opt-viewer/style.css new file mode 100644 index 00000000000..2ef244a1571 --- /dev/null +++ b/gnu/llvm/utils/opt-viewer/style.css @@ -0,0 +1,192 @@ +.red { + background-color: #ffd0d0; +} +.cyan { + background-color: cyan; +} +body { + font-family: -apple-system, sans-serif; +} +pre { + margin-top: 0px !important; + margin-bottom: 0px !important; +} +.source-name-title { + padding: 5px 10px; + border-bottom: 1px solid #dbdbdb; + background-color: #eee; + line-height: 35px; +} +.centered { + display: table; + margin-left: left; + margin-right: auto; + border: 1px solid #dbdbdb; + border-radius: 3px; +} +.expansion-view { + background-color: rgba(0, 0, 0, 0); + margin-left: 0px; + margin-top: 5px; + margin-right: 5px; + margin-bottom: 5px; + border: 1px solid #dbdbdb; + border-radius: 3px; +} +table { + border-collapse: collapse; +} +.light-row { + background: #ffffff; + border: 1px solid #dbdbdb; +} +.column-entry { + text-align: right; +} +.column-entry-left { + text-align: left; +} +.column-entry-white { + text-align: right; + background-color: #ffffff; +} +.column-entry-red { + text-align: right; + background-color: #ffd0d0; +} +.column-entry-green { + text-align: right; + background-color: #d0ffd0; +} +.column-entry-yellow { + text-align: left; + background-color: #ffe1a6; +} +.line-number { + text-align: right; + color: #aaa; +} +.covered-line { + text-align: right; + color: #0080ff; +} +.uncovered-line { + text-align: right; + color: #ff3300; +} +.tooltip { + position: relative; + display: inline; + background-color: #b3e6ff; + text-decoration: none; +} +.tooltip span.tooltip-content { + position: absolute; + width: 100px; + margin-left: -50px; + color: #FFFFFF; + background: #000000; + height: 30px; + line-height: 30px; + text-align: center; + visibility: hidden; + border-radius: 6px; +} +.tooltip span.tooltip-content:after { + content: ''; + position: absolute; + top: 100%; + left: 50%; + margin-left: -8px; + width: 0; height: 0; + border-top: 8px solid #000000; + border-right: 8px solid transparent; + border-left: 8px solid transparent; +} +:hover.tooltip span.tooltip-content { + visibility: visible; + opacity: 0.8; + bottom: 30px; + left: 50%; + z-index: 999; +} +th, td { + vertical-align: top; + padding: 2px 5px; + border-collapse: collapse; + border-right: solid 1px #eee; + border-left: solid 1px #eee; +} +td:first-child { + border-left: none; +} +td:last-child { + border-right: none; +} + +/* Generated with pygmentize -S colorful -f html >> style.css */ + +.hll { background-color: #ffffcc } +.c { color: #888888 } /* Comment */ +.err { color: #FF0000; background-color: #FFAAAA } /* Error */ +.k { color: #008800; font-weight: bold } /* Keyword */ +.o { color: #333333 } /* Operator */ +.ch { color: #888888 } /* Comment.Hashbang */ +.cm { color: #888888 } /* Comment.Multiline */ +.cp { color: #557799 } /* Comment.Preproc */ +.cpf { color: #888888 } /* Comment.PreprocFile */ +.c1 { color: #888888 } /* Comment.Single */ +.cs { color: #cc0000; font-weight: bold } /* Comment.Special */ +.gd { color: #A00000 } /* Generic.Deleted */ +.ge { font-style: italic } /* Generic.Emph */ +.gr { color: #FF0000 } /* Generic.Error */ +.gh { color: #000080; font-weight: bold } /* Generic.Heading */ +.gi { color: #00A000 } /* Generic.Inserted */ +.go { color: #888888 } /* Generic.Output */ +.gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */ +.gs { font-weight: bold } /* Generic.Strong */ +.gu { color: #800080; font-weight: bold } /* Generic.Subheading */ +.gt { color: #0044DD } /* Generic.Traceback */ +.kc { color: #008800; font-weight: bold } /* Keyword.Constant */ +.kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ +.kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ +.kp { color: #003388; font-weight: bold } /* Keyword.Pseudo */ +.kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ +.kt { color: #333399; font-weight: bold } /* Keyword.Type */ +.m { color: #6600EE; font-weight: bold } /* Literal.Number */ +.s { background-color: #fff0f0 } /* Literal.String */ +.na { color: #0000CC } /* Name.Attribute */ +.nb { color: #007020 } /* Name.Builtin */ +.nc { color: #BB0066; font-weight: bold } /* Name.Class */ +.no { color: #003366; font-weight: bold } /* Name.Constant */ +.nd { color: #555555; font-weight: bold } /* Name.Decorator */ +.ni { color: #880000; font-weight: bold } /* Name.Entity */ +.ne { color: #FF0000; font-weight: bold } /* Name.Exception */ +.nf { color: #0066BB; font-weight: bold } /* Name.Function */ +.nl { color: #997700; font-weight: bold } /* Name.Label */ +.nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */ +.nt { color: #007700 } /* Name.Tag */ +.nv { color: #996633 } /* Name.Variable */ +.ow { color: #000000; font-weight: bold } /* Operator.Word */ +.w { color: #bbbbbb } /* Text.Whitespace */ +.mb { color: #6600EE; font-weight: bold } /* Literal.Number.Bin */ +.mf { color: #6600EE; font-weight: bold } /* Literal.Number.Float */ +.mh { color: #005588; font-weight: bold } /* Literal.Number.Hex */ +.mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ +.mo { color: #4400EE; font-weight: bold } /* Literal.Number.Oct */ +.sb { background-color: #fff0f0 } /* Literal.String.Backtick */ +.sc { color: #0044DD } /* Literal.String.Char */ +.sd { color: #DD4422 } /* Literal.String.Doc */ +.s2 { background-color: #fff0f0 } /* Literal.String.Double */ +.se { color: #666666; font-weight: bold; background-color: #fff0f0 } /* Literal.String.Escape */ +.sh { background-color: #fff0f0 } /* Literal.String.Heredoc */ +.si { background-color: #eeeeee } /* Literal.String.Interpol */ +.sx { color: #DD2200; background-color: #fff0f0 } /* Literal.String.Other */ +.sr { color: #000000; background-color: #fff0ff } /* Literal.String.Regex */ +.s1 { background-color: #fff0f0 } /* Literal.String.Single */ +.ss { color: #AA6600 } /* Literal.String.Symbol */ +.bp { color: #007020 } /* Name.Builtin.Pseudo */ +.vc { color: #336699 } /* Name.Variable.Class */ +.vg { color: #dd7700; font-weight: bold } /* Name.Variable.Global */ +.vi { color: #3333BB } /* Name.Variable.Instance */ +.il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */ diff --git a/gnu/llvm/utils/prepare-code-coverage-artifact.py b/gnu/llvm/utils/prepare-code-coverage-artifact.py index e233c2c6efe..726375e899c 100644 --- a/gnu/llvm/utils/prepare-code-coverage-artifact.py +++ b/gnu/llvm/utils/prepare-code-coverage-artifact.py @@ -1,10 +1,11 @@ #!/usr/bin/env python +from __future__ import print_function + '''Prepare a code coverage artifact. - Collate raw profiles into one indexed profile. -- Delete the raw profiles. -- Copy the coverage mappings in the binaries directory. +- Generate html reports for the given binaries. ''' import argparse @@ -13,8 +14,8 @@ import os import subprocess import sys -def merge_raw_profiles(host_llvm_profdata, profile_data_dir): - print ':: Merging raw profiles...', +def merge_raw_profiles(host_llvm_profdata, profile_data_dir, preserve_profiles): + print(':: Merging raw profiles...', end='') sys.stdout.flush() raw_profiles = glob.glob(os.path.join(profile_data_dir, '*.profraw')) manifest_path = os.path.join(profile_data_dir, 'profiles.manifest') @@ -23,22 +24,44 @@ def merge_raw_profiles(host_llvm_profdata, profile_data_dir): manifest.write('\n'.join(raw_profiles)) subprocess.check_call([host_llvm_profdata, 'merge', '-sparse', '-f', manifest_path, '-o', profdata_path]) - for raw_profile in raw_profiles: - os.remove(raw_profile) - print 'Done!' + if not preserve_profiles: + for raw_profile in raw_profiles: + os.remove(raw_profile) + os.remove(manifest_path) + print('Done!') + return profdata_path -def extract_covmappings(host_llvm_cov, profile_data_dir, llvm_bin_dir): - print ':: Extracting covmappings...', +def prepare_html_report(host_llvm_cov, profile, report_dir, binaries, + restricted_dirs): + print(':: Preparing html report for {0}...'.format(binaries), end='') sys.stdout.flush() - for prog in os.listdir(llvm_bin_dir): - if prog == 'llvm-lit': - continue - covmapping_path = os.path.join(profile_data_dir, - os.path.basename(prog) + '.covmapping') - subprocess.check_call([host_llvm_cov, 'convert-for-testing', - os.path.join(llvm_bin_dir, prog), '-o', - covmapping_path]) - print 'Done!' + objects = [] + for i, binary in enumerate(binaries): + if i == 0: + objects.append(binary) + else: + objects.extend(('-object', binary)) + invocation = [host_llvm_cov, 'show'] + objects + ['-format', 'html', + '-instr-profile', profile, '-o', report_dir, + '-show-line-counts-or-regions', '-Xdemangler', 'c++filt', + '-Xdemangler', '-n'] + restricted_dirs + subprocess.check_call(invocation) + with open(os.path.join(report_dir, 'summary.txt'), 'wb') as Summary: + subprocess.check_call([host_llvm_cov, 'report'] + objects + + ['-instr-profile', profile], stdout=Summary) + print('Done!') + +def prepare_html_reports(host_llvm_cov, profdata_path, report_dir, binaries, + unified_report, restricted_dirs): + if unified_report: + prepare_html_report(host_llvm_cov, profdata_path, report_dir, binaries, + restricted_dirs) + else: + for binary in binaries: + binary_report_dir = os.path.join(report_dir, + os.path.basename(binary)) + prepare_html_report(host_llvm_cov, profdata_path, binary_report_dir, + [binary], restricted_dirs) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) @@ -46,10 +69,39 @@ if __name__ == '__main__': parser.add_argument('host_llvm_cov', help='Path to llvm-cov') parser.add_argument('profile_data_dir', help='Path to the directory containing the raw profiles') - parser.add_argument('llvm_bin_dir', - help='Path to the directory containing llvm binaries') + parser.add_argument('report_dir', + help='Path to the output directory for html reports') + parser.add_argument('binaries', metavar='B', type=str, nargs='*', + help='Path to an instrumented binary') + parser.add_argument('--only-merge', action='store_true', + help='Only merge raw profiles together, skip report ' + 'generation') + parser.add_argument('--preserve-profiles', + help='Do not delete raw profiles', action='store_true') + parser.add_argument('--use-existing-profdata', + help='Specify an existing indexed profile to use') + parser.add_argument('--unified-report', action='store_true', + help='Emit a unified report for all binaries') + parser.add_argument('--restrict', metavar='R', type=str, nargs='*', + default=[], + help='Restrict the reporting to the given source paths') args = parser.parse_args() - merge_raw_profiles(args.host_llvm_profdata, args.profile_data_dir) - extract_covmappings(args.host_llvm_cov, args.profile_data_dir, - args.llvm_bin_dir) + if args.use_existing_profdata and args.only_merge: + print('--use-existing-profdata and --only-merge are incompatible') + exit(1) + + if args.use_existing_profdata: + profdata_path = args.use_existing_profdata + else: + profdata_path = merge_raw_profiles(args.host_llvm_profdata, + args.profile_data_dir, + args.preserve_profiles) + + if not len(args.binaries): + print('No binaries specified, no work to do!') + exit(1) + + if not args.only_merge: + prepare_html_reports(args.host_llvm_cov, profdata_path, args.report_dir, + args.binaries, args.unified_report, args.restrict) diff --git a/gnu/llvm/utils/release/build_llvm_package.bat b/gnu/llvm/utils/release/build_llvm_package.bat index 5542ca613f3..e7895157cd0 100755 --- a/gnu/llvm/utils/release/build_llvm_package.bat +++ b/gnu/llvm/utils/release/build_llvm_package.bat @@ -8,19 +8,25 @@ REM Usage: build_llvm_package.bat <revision> REM Prerequisites:
REM
-REM Visual Studio 2013, CMake, Ninja, SVN, GNUWin32,
+REM Visual Studio 2015, CMake, Ninja, SVN, GNUWin32, SWIG, Python 3,
REM NSIS with the strlen_8192 patch,
-REM Visual Studio 2013 SDK (for the clang-format plugin).
+REM Visual Studio 2015 SDK (for the clang-format plugin).
+REM
+REM
+REM For LLDB, SWIG version <= 3.0.8 needs to be used to work around
+REM https://github.com/swig/swig/issues/769
-REM You may need to modify the paths below:
-set vcdir=c:\Program Files (x86)\Microsoft Visual Studio 12.0\VC
+REM You need to modify the paths below:
+set vcdir=c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC
+set python32_dir=C:\Users\hwennborg\AppData\Local\Programs\Python\Python35-32
+set python64_dir=C:\Users\hwennborg\AppData\Local\Programs\Python\Python35
set PATH=%PATH%;c:\gnuwin32\bin
set revision=%1
set branch=trunk
-set package_version=3.9.0-r%revision%
-set clang_format_vs_version=3.9.0.%revision%
+set package_version=4.0.0-r%revision%
+set clang_format_vs_version=4.0.0.%revision%
set build_dir=llvm_package_%revision%
echo Branch: %branch%
@@ -41,10 +47,11 @@ svn.exe export -r %revision% http://llvm.org/svn/llvm-project/clang-tools-extra/ svn.exe export -r %revision% http://llvm.org/svn/llvm-project/lld/%branch% llvm/tools/lld || exit /b
svn.exe export -r %revision% http://llvm.org/svn/llvm-project/compiler-rt/%branch% llvm/projects/compiler-rt || exit /b
svn.exe export -r %revision% http://llvm.org/svn/llvm-project/openmp/%branch% llvm/projects/openmp || exit /b
+svn.exe export -r %revision% http://llvm.org/svn/llvm-project/lldb/%branch% llvm/tools/lldb || exit /b
REM Setting CMAKE_CL_SHOWINCLUDES_PREFIX to work around PR27226.
-set cmake_flags=-DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON -DLLVM_INSTALL_TOOLCHAIN_ONLY=ON -DLLVM_USE_CRT_RELEASE=MT -DCLANG_FORMAT_VS_VERSION=%clang_format_vs_version% -DPACKAGE_VERSION=%package_version% -DCMAKE_CL_SHOWINCLUDES_PREFIX="Note: including file: "
+set cmake_flags=-DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON -DLLVM_INSTALL_TOOLCHAIN_ONLY=ON -DLLVM_USE_CRT_RELEASE=MT -DCLANG_FORMAT_VS_VERSION=%clang_format_vs_version% -DPACKAGE_VERSION=%package_version% -DLLDB_RELOCATABLE_PYTHON=1 -DLLDB_TEST_COMPILER=%cd%\build32_stage0\bin\clang.exe -DCMAKE_CL_SHOWINCLUDES_PREFIX="Note: including file: "
REM TODO: Run all tests, including lld and compiler-rt.
@@ -53,20 +60,20 @@ set CC= set CXX=
mkdir build32_stage0
cd build32_stage0
-cmake -GNinja %cmake_flags% ..\llvm || exit /b
+cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python32_dir% ..\llvm || exit /b
ninja all || exit /b
-ninja check || exit /b
-ninja check-clang || exit /b
+ninja check || ninja check || ninja check || exit /b
+ninja check-clang || ninja check-clang || ninja check-clang || exit /b
cd..
mkdir build32
cd build32
set CC=..\build32_stage0\bin\clang-cl
set CXX=..\build32_stage0\bin\clang-cl
-cmake -GNinja %cmake_flags% -DBUILD_CLANG_FORMAT_VS_PLUGIN=ON ..\llvm || exit /b
+cmake -GNinja %cmake_flags% -DBUILD_CLANG_FORMAT_VS_PLUGIN=ON -DPYTHON_HOME=%python32_dir% ..\llvm || exit /b
ninja all || exit /b
-ninja check || exit /b
-ninja check-clang || exit /b
+ninja check || ninja check || ninja check || exit /b
+ninja check-clang || ninja check-clang || ninja check-clang || exit /b
copy ..\llvm\tools\clang\tools\clang-format-vs\ClangFormat\bin\Release\ClangFormat.vsix ClangFormat-r%revision%.vsix
ninja package || exit /b
cd ..
@@ -77,19 +84,19 @@ set CC= set CXX=
mkdir build64_stage0
cd build64_stage0
-cmake -GNinja %cmake_flags% ..\llvm || exit /b
+cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python64_dir% ..\llvm || exit /b
ninja all || exit /b
-ninja check || exit /b
-ninja check-clang || exit /b
+ninja check || ninja check || ninja check || exit /b
+ninja check-clang || ninja check-clang || ninja check-clang || exit /b
cd..
mkdir build64
cd build64
set CC=..\build64_stage0\bin\clang-cl
set CXX=..\build64_stage0\bin\clang-cl
-cmake -GNinja %cmake_flags% ..\llvm || exit /b
+cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python64_dir% ..\llvm || exit /b
ninja all || exit /b
-ninja check || exit /b
-ninja check-clang || exit /b
+ninja check || ninja check || ninja check || exit /b
+ninja check-clang || ninja check-clang || ninja check-clang || exit /b
ninja package || exit /b
cd ..
diff --git a/gnu/llvm/utils/release/merge.sh b/gnu/llvm/utils/release/merge.sh index b4893224834..698353d6915 100755 --- a/gnu/llvm/utils/release/merge.sh +++ b/gnu/llvm/utils/release/merge.sh @@ -95,7 +95,7 @@ else fi echo -echo "# To commit, run the following in $proj.src/:" +echo "# To commit, run the following in $srcdir/:" echo svn commit -F $tempfile exit 0 diff --git a/gnu/llvm/utils/release/test-release.sh b/gnu/llvm/utils/release/test-release.sh index b9cc38d35e2..73e31d46d51 100755 --- a/gnu/llvm/utils/release/test-release.sh +++ b/gnu/llvm/utils/release/test-release.sh @@ -355,13 +355,11 @@ function configure_llvmCore() { echo "#" env CC="$c_compiler" CXX="$cxx_compiler" \ cmake -G "Unix Makefiles" \ -DCMAKE_BUILD_TYPE=$BuildType -DLLVM_ENABLE_ASSERTIONS=$Assertions \ - -DLLVM_CONFIGTIME="(timestamp not enabled)" \ $ExtraConfigureFlags $BuildDir/llvm.src \ 2>&1 | tee $LogDir/llvm.configure-Phase$Phase-$Flavor.log env CC="$c_compiler" CXX="$cxx_compiler" \ cmake -G "Unix Makefiles" \ -DCMAKE_BUILD_TYPE=$BuildType -DLLVM_ENABLE_ASSERTIONS=$Assertions \ - -DLLVM_CONFIGTIME="(timestamp not enabled)" \ $ExtraConfigureFlags $BuildDir/llvm.src \ 2>&1 | tee $LogDir/llvm.configure-Phase$Phase-$Flavor.log diff --git a/gnu/llvm/utils/unittest/CMakeLists.txt b/gnu/llvm/utils/unittest/CMakeLists.txt index c9a2cdd45c8..a50733af9aa 100644 --- a/gnu/llvm/utils/unittest/CMakeLists.txt +++ b/gnu/llvm/utils/unittest/CMakeLists.txt @@ -15,15 +15,23 @@ include_directories( googletest/include googletest + googlemock/include + googlemock ) if(WIN32) add_definitions(-DGTEST_OS_WINDOWS=1) endif() -if(SUPPORTS_NO_VARIADIC_MACROS_FLAG) +if(SUPPORTS_VARIADIC_MACROS_FLAG) add_definitions("-Wno-variadic-macros") endif() +if(SUPPORTS_GNU_ZERO_VARIADIC_MACRO_ARGUMENTS_FLAG) + add_definitions("-Wno-gnu-zero-variadic-macro-arguments") +endif() +if(CXX_SUPPORTS_COVERED_SWITCH_DEFAULT_FLAG) + add_definitions("-Wno-covered-switch-default") +endif() set(LLVM_REQUIRES_RTTI 1) add_definitions( -DGTEST_HAS_RTTI=0 ) @@ -39,12 +47,16 @@ endif() add_llvm_library(gtest googletest/src/gtest-all.cc + googlemock/src/gmock-all.cc LINK_LIBS ${LIBS} LINK_COMPONENTS Support # Depends on llvm::raw_ostream + + # This is a library meant only for the build tree. + BUILDTREE_ONLY ) add_subdirectory(UnitTestMain) diff --git a/gnu/llvm/utils/unittest/UnitTestMain/CMakeLists.txt b/gnu/llvm/utils/unittest/UnitTestMain/CMakeLists.txt index 520db4e8d2b..32f0f25a60f 100644 --- a/gnu/llvm/utils/unittest/UnitTestMain/CMakeLists.txt +++ b/gnu/llvm/utils/unittest/UnitTestMain/CMakeLists.txt @@ -6,4 +6,7 @@ add_llvm_library(gtest_main LINK_COMPONENTS Support # Depends on llvm::cl + + # This library is not meant to be in the install tree, only the build tree. + BUILDTREE_ONLY ) diff --git a/gnu/llvm/utils/unittest/UnitTestMain/TestMain.cpp b/gnu/llvm/utils/unittest/UnitTestMain/TestMain.cpp index 36cec2d4742..5660b44f41a 100644 --- a/gnu/llvm/utils/unittest/UnitTestMain/TestMain.cpp +++ b/gnu/llvm/utils/unittest/UnitTestMain/TestMain.cpp @@ -9,9 +9,9 @@ #include "llvm/Support/CommandLine.h" #include "llvm/Support/Signals.h" +#include "gmock/gmock.h" #include "gtest/gtest.h" - #if defined(_WIN32) # include <windows.h> # if defined(_MSC_VER) @@ -24,7 +24,10 @@ const char *TestMainArgv0; int main(int argc, char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(argv[0], true /* Disable crash reporting */); - testing::InitGoogleTest(&argc, argv); + + // Initialize both gmock and gtest. + testing::InitGoogleMock(&argc, argv); + llvm::cl::ParseCommandLineOptions(argc, argv); // Make it easy for a test to re-execute itself by saving argv[0]. diff --git a/gnu/llvm/utils/unittest/googlemock/LICENSE.txt b/gnu/llvm/utils/unittest/googlemock/LICENSE.txt new file mode 100644 index 00000000000..1941a11f8ce --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/gnu/llvm/utils/unittest/googlemock/README.LLVM b/gnu/llvm/utils/unittest/googlemock/README.LLVM new file mode 100644 index 00000000000..9badc7d4a70 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/README.LLVM @@ -0,0 +1,17 @@ +LLVM notes +---------- + +This directory contains the 'googlemock' component of Google Test 1.8.0, with +all elements removed except for the actual source code, to minimize the +addition to the LLVM distribution. + +Cleaned up as follows: + +# Remove all the unnecessary files and directories +$ rm -f CMakeLists.txt configure* Makefile* CHANGES CONTRIBUTORS README README.md .gitignore +$ rm -rf build-aux make msvc scripts test docs +$ rm -f `find . -name \*\.pump` +$ rm -f src/gmock_main.cc + +# Put the license in the consistent place for LLVM. +$ mv LICENSE LICENSE.TXT diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-actions.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-actions.h new file mode 100644 index 00000000000..b3f654af348 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-actions.h @@ -0,0 +1,1205 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some commonly used actions. + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ + +#ifndef _WIN32_WCE +# include <errno.h> +#endif + +#include <algorithm> +#include <string> + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" + +#if GTEST_HAS_STD_TYPE_TRAITS_ // Defined by gtest-port.h via gmock-port.h. +#include <type_traits> +#endif + +namespace testing { + +// To implement an action Foo, define: +// 1. a class FooAction that implements the ActionInterface interface, and +// 2. a factory function that creates an Action object from a +// const FooAction*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Action objects can now be copied like plain values. + +namespace internal { + +template <typename F1, typename F2> +class ActionAdaptor; + +// BuiltInDefaultValueGetter<T, true>::Get() returns a +// default-constructed T value. BuiltInDefaultValueGetter<T, +// false>::Get() crashes with an error. +// +// This primary template is used when kDefaultConstructible is true. +template <typename T, bool kDefaultConstructible> +struct BuiltInDefaultValueGetter { + static T Get() { return T(); } +}; +template <typename T> +struct BuiltInDefaultValueGetter<T, false> { + static T Get() { + Assert(false, __FILE__, __LINE__, + "Default action undefined for the function return type."); + return internal::Invalid<T>(); + // The above statement will never be reached, but is required in + // order for this function to compile. + } +}; + +// BuiltInDefaultValue<T>::Get() returns the "built-in" default value +// for type T, which is NULL when T is a raw pointer type, 0 when T is +// a numeric type, false when T is bool, or "" when T is string or +// std::string. In addition, in C++11 and above, it turns a +// default-constructed T value if T is default constructible. For any +// other type T, the built-in default T value is undefined, and the +// function will abort the process. +template <typename T> +class BuiltInDefaultValue { + public: +#if GTEST_HAS_STD_TYPE_TRAITS_ + // This function returns true iff type T has a built-in default value. + static bool Exists() { + return ::std::is_default_constructible<T>::value; + } + + static T Get() { + return BuiltInDefaultValueGetter< + T, ::std::is_default_constructible<T>::value>::Get(); + } + +#else // GTEST_HAS_STD_TYPE_TRAITS_ + // This function returns true iff type T has a built-in default value. + static bool Exists() { + return false; + } + + static T Get() { + return BuiltInDefaultValueGetter<T, false>::Get(); + } + +#endif // GTEST_HAS_STD_TYPE_TRAITS_ +}; + +// This partial specialization says that we use the same built-in +// default value for T and const T. +template <typename T> +class BuiltInDefaultValue<const T> { + public: + static bool Exists() { return BuiltInDefaultValue<T>::Exists(); } + static T Get() { return BuiltInDefaultValue<T>::Get(); } +}; + +// This partial specialization defines the default values for pointer +// types. +template <typename T> +class BuiltInDefaultValue<T*> { + public: + static bool Exists() { return true; } + static T* Get() { return NULL; } +}; + +// The following specializations define the default values for +// specific types we care about. +#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ + template <> \ + class BuiltInDefaultValue<type> { \ + public: \ + static bool Exists() { return true; } \ + static type Get() { return value; } \ + } + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT +#if GTEST_HAS_GLOBAL_STRING +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, ""); +#endif // GTEST_HAS_GLOBAL_STRING +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); + +// There's no need for a default action for signed wchar_t, as that +// type is the same as wchar_t for gcc, and invalid for MSVC. +// +// There's also no need for a default action for unsigned wchar_t, as +// that type is the same as unsigned int for gcc, and invalid for +// MSVC. +#if GMOCK_WCHAR_T_IS_NATIVE_ +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT +#endif + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); + +#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ + +} // namespace internal + +// When an unexpected function call is encountered, Google Mock will +// let it return a default value if the user has specified one for its +// return type, or if the return type has a built-in default value; +// otherwise Google Mock won't know what value to return and will have +// to abort the process. +// +// The DefaultValue<T> class allows a user to specify the +// default value for a type T that is both copyable and publicly +// destructible (i.e. anything that can be used as a function return +// type). The usage is: +// +// // Sets the default value for type T to be foo. +// DefaultValue<T>::Set(foo); +template <typename T> +class DefaultValue { + public: + // Sets the default value for type T; requires T to be + // copy-constructable and have a public destructor. + static void Set(T x) { + delete producer_; + producer_ = new FixedValueProducer(x); + } + + // Provides a factory function to be called to generate the default value. + // This method can be used even if T is only move-constructible, but it is not + // limited to that case. + typedef T (*FactoryFunction)(); + static void SetFactory(FactoryFunction factory) { + delete producer_; + producer_ = new FactoryValueProducer(factory); + } + + // Unsets the default value for type T. + static void Clear() { + delete producer_; + producer_ = NULL; + } + + // Returns true iff the user has set the default value for type T. + static bool IsSet() { return producer_ != NULL; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue<T>::Exists(); + } + + // Returns the default value for type T if the user has set one; + // otherwise returns the built-in default value. Requires that Exists() + // is true, which ensures that the return value is well-defined. + static T Get() { + return producer_ == NULL ? + internal::BuiltInDefaultValue<T>::Get() : producer_->Produce(); + } + + private: + class ValueProducer { + public: + virtual ~ValueProducer() {} + virtual T Produce() = 0; + }; + + class FixedValueProducer : public ValueProducer { + public: + explicit FixedValueProducer(T value) : value_(value) {} + virtual T Produce() { return value_; } + + private: + const T value_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer); + }; + + class FactoryValueProducer : public ValueProducer { + public: + explicit FactoryValueProducer(FactoryFunction factory) + : factory_(factory) {} + virtual T Produce() { return factory_(); } + + private: + const FactoryFunction factory_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer); + }; + + static ValueProducer* producer_; +}; + +// This partial specialization allows a user to set default values for +// reference types. +template <typename T> +class DefaultValue<T&> { + public: + // Sets the default value for type T&. + static void Set(T& x) { // NOLINT + address_ = &x; + } + + // Unsets the default value for type T&. + static void Clear() { + address_ = NULL; + } + + // Returns true iff the user has set the default value for type T&. + static bool IsSet() { return address_ != NULL; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue<T&>::Exists(); + } + + // Returns the default value for type T& if the user has set one; + // otherwise returns the built-in default value if there is one; + // otherwise aborts the process. + static T& Get() { + return address_ == NULL ? + internal::BuiltInDefaultValue<T&>::Get() : *address_; + } + + private: + static T* address_; +}; + +// This specialization allows DefaultValue<void>::Get() to +// compile. +template <> +class DefaultValue<void> { + public: + static bool Exists() { return true; } + static void Get() {} +}; + +// Points to the user-set default value for type T. +template <typename T> +typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL; + +// Points to the user-set default value for type T&. +template <typename T> +T* DefaultValue<T&>::address_ = NULL; + +// Implement this interface to define an action for function type F. +template <typename F> +class ActionInterface { + public: + typedef typename internal::Function<F>::Result Result; + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + ActionInterface() {} + virtual ~ActionInterface() {} + + // Performs the action. This method is not const, as in general an + // action can have side effects and be stateful. For example, a + // get-the-next-element-from-the-collection action will need to + // remember the current element. + virtual Result Perform(const ArgumentTuple& args) = 0; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface); +}; + +// An Action<F> is a copyable and IMMUTABLE (except by assignment) +// object that represents an action to be taken when a mock function +// of type F is called. The implementation of Action<T> is just a +// linked_ptr to const ActionInterface<T>, so copying is fairly cheap. +// Don't inherit from Action! +// +// You can view an object implementing ActionInterface<F> as a +// concrete action (including its current state), and an Action<F> +// object as a handle to it. +template <typename F> +class Action { + public: + typedef typename internal::Function<F>::Result Result; + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + // Constructs a null Action. Needed for storing Action objects in + // STL containers. + Action() : impl_(NULL) {} + + // Constructs an Action from its implementation. A NULL impl is + // used to represent the "do-default" action. + explicit Action(ActionInterface<F>* impl) : impl_(impl) {} + + // Copy constructor. + Action(const Action& action) : impl_(action.impl_) {} + + // This constructor allows us to turn an Action<Func> object into an + // Action<F>, as long as F's arguments can be implicitly converted + // to Func's and Func's return type can be implicitly converted to + // F's. + template <typename Func> + explicit Action(const Action<Func>& action); + + // Returns true iff this is the DoDefault() action. + bool IsDoDefault() const { return impl_.get() == NULL; } + + // Performs the action. Note that this method is const even though + // the corresponding method in ActionInterface is not. The reason + // is that a const Action<F> means that it cannot be re-bound to + // another concrete action, not that the concrete action it binds to + // cannot change state. (Think of the difference between a const + // pointer and a pointer to const.) + Result Perform(const ArgumentTuple& args) const { + internal::Assert( + !IsDoDefault(), __FILE__, __LINE__, + "You are using DoDefault() inside a composite action like " + "DoAll() or WithArgs(). This is not supported for technical " + "reasons. Please instead spell out the default action, or " + "assign the default action to an Action variable and use " + "the variable in various places."); + return impl_->Perform(args); + } + + private: + template <typename F1, typename F2> + friend class internal::ActionAdaptor; + + internal::linked_ptr<ActionInterface<F> > impl_; +}; + +// The PolymorphicAction class template makes it easy to implement a +// polymorphic action (i.e. an action that can be used in mock +// functions of than one type, e.g. Return()). +// +// To define a polymorphic action, a user first provides a COPYABLE +// implementation class that has a Perform() method template: +// +// class FooAction { +// public: +// template <typename Result, typename ArgumentTuple> +// Result Perform(const ArgumentTuple& args) const { +// // Processes the arguments and returns a result, using +// // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple. +// } +// ... +// }; +// +// Then the user creates the polymorphic action using +// MakePolymorphicAction(object) where object has type FooAction. See +// the definition of Return(void) and SetArgumentPointee<N>(value) for +// complete examples. +template <typename Impl> +class PolymorphicAction { + public: + explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} + + template <typename F> + operator Action<F>() const { + return Action<F>(new MonomorphicImpl<F>(impl_)); + } + + private: + template <typename F> + class MonomorphicImpl : public ActionInterface<F> { + public: + typedef typename internal::Function<F>::Result Result; + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} + + virtual Result Perform(const ArgumentTuple& args) { + return impl_.template Perform<Result>(args); + } + + private: + Impl impl_; + + GTEST_DISALLOW_ASSIGN_(MonomorphicImpl); + }; + + Impl impl_; + + GTEST_DISALLOW_ASSIGN_(PolymorphicAction); +}; + +// Creates an Action from its implementation and returns it. The +// created Action object owns the implementation. +template <typename F> +Action<F> MakeAction(ActionInterface<F>* impl) { + return Action<F>(impl); +} + +// Creates a polymorphic action from its implementation. This is +// easier to use than the PolymorphicAction<Impl> constructor as it +// doesn't require you to explicitly write the template argument, e.g. +// +// MakePolymorphicAction(foo); +// vs +// PolymorphicAction<TypeOfFoo>(foo); +template <typename Impl> +inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) { + return PolymorphicAction<Impl>(impl); +} + +namespace internal { + +// Allows an Action<F2> object to pose as an Action<F1>, as long as F2 +// and F1 are compatible. +template <typename F1, typename F2> +class ActionAdaptor : public ActionInterface<F1> { + public: + typedef typename internal::Function<F1>::Result Result; + typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple; + + explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {} + + virtual Result Perform(const ArgumentTuple& args) { + return impl_->Perform(args); + } + + private: + const internal::linked_ptr<ActionInterface<F2> > impl_; + + GTEST_DISALLOW_ASSIGN_(ActionAdaptor); +}; + +// Helper struct to specialize ReturnAction to execute a move instead of a copy +// on return. Useful for move-only types, but could be used on any type. +template <typename T> +struct ByMoveWrapper { + explicit ByMoveWrapper(T value) : payload(internal::move(value)) {} + T payload; +}; + +// Implements the polymorphic Return(x) action, which can be used in +// any function that returns the type of x, regardless of the argument +// types. +// +// Note: The value passed into Return must be converted into +// Function<F>::Result when this action is cast to Action<F> rather than +// when that action is performed. This is important in scenarios like +// +// MOCK_METHOD1(Method, T(U)); +// ... +// { +// Foo foo; +// X x(&foo); +// EXPECT_CALL(mock, Method(_)).WillOnce(Return(x)); +// } +// +// In the example above the variable x holds reference to foo which leaves +// scope and gets destroyed. If copying X just copies a reference to foo, +// that copy will be left with a hanging reference. If conversion to T +// makes a copy of foo, the above code is safe. To support that scenario, we +// need to make sure that the type conversion happens inside the EXPECT_CALL +// statement, and conversion of the result of Return to Action<T(U)> is a +// good place for that. +// +template <typename R> +class ReturnAction { + public: + // Constructs a ReturnAction object from the value to be returned. + // 'value' is passed by value instead of by const reference in order + // to allow Return("string literal") to compile. + explicit ReturnAction(R value) : value_(new R(internal::move(value))) {} + + // This template type conversion operator allows Return(x) to be + // used in ANY function that returns x's type. + template <typename F> + operator Action<F>() const { + // Assert statement belongs here because this is the best place to verify + // conditions on F. It produces the clearest error messages + // in most compilers. + // Impl really belongs in this scope as a local class but can't + // because MSVC produces duplicate symbols in different translation units + // in this case. Until MS fixes that bug we put Impl into the class scope + // and put the typedef both here (for use in assert statement) and + // in the Impl class. But both definitions must be the same. + typedef typename Function<F>::Result Result; + GTEST_COMPILE_ASSERT_( + !is_reference<Result>::value, + use_ReturnRef_instead_of_Return_to_return_a_reference); + return Action<F>(new Impl<R, F>(value_)); + } + + private: + // Implements the Return(x) action for a particular function type F. + template <typename R_, typename F> + class Impl : public ActionInterface<F> { + public: + typedef typename Function<F>::Result Result; + typedef typename Function<F>::ArgumentTuple ArgumentTuple; + + // The implicit cast is necessary when Result has more than one + // single-argument constructor (e.g. Result is std::vector<int>) and R + // has a type conversion operator template. In that case, value_(value) + // won't compile as the compiler doesn't known which constructor of + // Result to call. ImplicitCast_ forces the compiler to convert R to + // Result without considering explicit constructors, thus resolving the + // ambiguity. value_ is then initialized using its copy constructor. + explicit Impl(const linked_ptr<R>& value) + : value_before_cast_(*value), + value_(ImplicitCast_<Result>(value_before_cast_)) {} + + virtual Result Perform(const ArgumentTuple&) { return value_; } + + private: + GTEST_COMPILE_ASSERT_(!is_reference<Result>::value, + Result_cannot_be_a_reference_type); + // We save the value before casting just in case it is being cast to a + // wrapper type. + R value_before_cast_; + Result value_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); + }; + + // Partially specialize for ByMoveWrapper. This version of ReturnAction will + // move its contents instead. + template <typename R_, typename F> + class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> { + public: + typedef typename Function<F>::Result Result; + typedef typename Function<F>::ArgumentTuple ArgumentTuple; + + explicit Impl(const linked_ptr<R>& wrapper) + : performed_(false), wrapper_(wrapper) {} + + virtual Result Perform(const ArgumentTuple&) { + GTEST_CHECK_(!performed_) + << "A ByMove() action should only be performed once."; + performed_ = true; + return internal::move(wrapper_->payload); + } + + private: + bool performed_; + const linked_ptr<R> wrapper_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + const linked_ptr<R> value_; + + GTEST_DISALLOW_ASSIGN_(ReturnAction); +}; + +// Implements the ReturnNull() action. +class ReturnNullAction { + public: + // Allows ReturnNull() to be used in any pointer-returning function. In C++11 + // this is enforced by returning nullptr, and in non-C++11 by asserting a + // pointer type on compile time. + template <typename Result, typename ArgumentTuple> + static Result Perform(const ArgumentTuple&) { +#if GTEST_LANG_CXX11 + return nullptr; +#else + GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value, + ReturnNull_can_be_used_to_return_a_pointer_only); + return NULL; +#endif // GTEST_LANG_CXX11 + } +}; + +// Implements the Return() action. +class ReturnVoidAction { + public: + // Allows Return() to be used in any void-returning function. + template <typename Result, typename ArgumentTuple> + static void Perform(const ArgumentTuple&) { + CompileAssertTypesEqual<void, Result>(); + } +}; + +// Implements the polymorphic ReturnRef(x) action, which can be used +// in any function that returns a reference to the type of x, +// regardless of the argument types. +template <typename T> +class ReturnRefAction { + public: + // Constructs a ReturnRefAction object from the reference to be returned. + explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT + + // This template type conversion operator allows ReturnRef(x) to be + // used in ANY function that returns a reference to x's type. + template <typename F> + operator Action<F>() const { + typedef typename Function<F>::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRef(x) when Return(x) + // should be used, and generates some helpful error message. + GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value, + use_Return_instead_of_ReturnRef_to_return_a_value); + return Action<F>(new Impl<F>(ref_)); + } + + private: + // Implements the ReturnRef(x) action for a particular function type F. + template <typename F> + class Impl : public ActionInterface<F> { + public: + typedef typename Function<F>::Result Result; + typedef typename Function<F>::ArgumentTuple ArgumentTuple; + + explicit Impl(T& ref) : ref_(ref) {} // NOLINT + + virtual Result Perform(const ArgumentTuple&) { + return ref_; + } + + private: + T& ref_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + T& ref_; + + GTEST_DISALLOW_ASSIGN_(ReturnRefAction); +}; + +// Implements the polymorphic ReturnRefOfCopy(x) action, which can be +// used in any function that returns a reference to the type of x, +// regardless of the argument types. +template <typename T> +class ReturnRefOfCopyAction { + public: + // Constructs a ReturnRefOfCopyAction object from the reference to + // be returned. + explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT + + // This template type conversion operator allows ReturnRefOfCopy(x) to be + // used in ANY function that returns a reference to x's type. + template <typename F> + operator Action<F>() const { + typedef typename Function<F>::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRefOfCopy(x) when Return(x) + // should be used, and generates some helpful error message. + GTEST_COMPILE_ASSERT_( + internal::is_reference<Result>::value, + use_Return_instead_of_ReturnRefOfCopy_to_return_a_value); + return Action<F>(new Impl<F>(value_)); + } + + private: + // Implements the ReturnRefOfCopy(x) action for a particular function type F. + template <typename F> + class Impl : public ActionInterface<F> { + public: + typedef typename Function<F>::Result Result; + typedef typename Function<F>::ArgumentTuple ArgumentTuple; + + explicit Impl(const T& value) : value_(value) {} // NOLINT + + virtual Result Perform(const ArgumentTuple&) { + return value_; + } + + private: + T value_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + const T value_; + + GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction); +}; + +// Implements the polymorphic DoDefault() action. +class DoDefaultAction { + public: + // This template type conversion operator allows DoDefault() to be + // used in any function. + template <typename F> + operator Action<F>() const { return Action<F>(NULL); } +}; + +// Implements the Assign action to set a given pointer referent to a +// particular value. +template <typename T1, typename T2> +class AssignAction { + public: + AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} + + template <typename Result, typename ArgumentTuple> + void Perform(const ArgumentTuple& /* args */) const { + *ptr_ = value_; + } + + private: + T1* const ptr_; + const T2 value_; + + GTEST_DISALLOW_ASSIGN_(AssignAction); +}; + +#if !GTEST_OS_WINDOWS_MOBILE + +// Implements the SetErrnoAndReturn action to simulate return from +// various system calls and libc functions. +template <typename T> +class SetErrnoAndReturnAction { + public: + SetErrnoAndReturnAction(int errno_value, T result) + : errno_(errno_value), + result_(result) {} + template <typename Result, typename ArgumentTuple> + Result Perform(const ArgumentTuple& /* args */) const { + errno = errno_; + return result_; + } + + private: + const int errno_; + const T result_; + + GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction); +}; + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Implements the SetArgumentPointee<N>(x) action for any function +// whose N-th argument (0-based) is a pointer to x's type. The +// template parameter kIsProto is true iff type A is ProtocolMessage, +// proto2::Message, or a sub-class of those. +template <size_t N, typename A, bool kIsProto> +class SetArgumentPointeeAction { + public: + // Constructs an action that sets the variable pointed to by the + // N-th function argument to 'value'. + explicit SetArgumentPointeeAction(const A& value) : value_(value) {} + + template <typename Result, typename ArgumentTuple> + void Perform(const ArgumentTuple& args) const { + CompileAssertTypesEqual<void, Result>(); + *::testing::get<N>(args) = value_; + } + + private: + const A value_; + + GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction); +}; + +template <size_t N, typename Proto> +class SetArgumentPointeeAction<N, Proto, true> { + public: + // Constructs an action that sets the variable pointed to by the + // N-th function argument to 'proto'. Both ProtocolMessage and + // proto2::Message have the CopyFrom() method, so the same + // implementation works for both. + explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) { + proto_->CopyFrom(proto); + } + + template <typename Result, typename ArgumentTuple> + void Perform(const ArgumentTuple& args) const { + CompileAssertTypesEqual<void, Result>(); + ::testing::get<N>(args)->CopyFrom(*proto_); + } + + private: + const internal::linked_ptr<Proto> proto_; + + GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction); +}; + +// Implements the InvokeWithoutArgs(f) action. The template argument +// FunctionImpl is the implementation type of f, which can be either a +// function pointer or a functor. InvokeWithoutArgs(f) can be used as an +// Action<F> as long as f's type is compatible with F (i.e. f can be +// assigned to a tr1::function<F>). +template <typename FunctionImpl> +class InvokeWithoutArgsAction { + public: + // The c'tor makes a copy of function_impl (either a function + // pointer or a functor). + explicit InvokeWithoutArgsAction(FunctionImpl function_impl) + : function_impl_(function_impl) {} + + // Allows InvokeWithoutArgs(f) to be used as any action whose type is + // compatible with f. + template <typename Result, typename ArgumentTuple> + Result Perform(const ArgumentTuple&) { return function_impl_(); } + + private: + FunctionImpl function_impl_; + + GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction); +}; + +// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. +template <class Class, typename MethodPtr> +class InvokeMethodWithoutArgsAction { + public: + InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr) + : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {} + + template <typename Result, typename ArgumentTuple> + Result Perform(const ArgumentTuple&) const { + return (obj_ptr_->*method_ptr_)(); + } + + private: + Class* const obj_ptr_; + const MethodPtr method_ptr_; + + GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction); +}; + +// Implements the IgnoreResult(action) action. +template <typename A> +class IgnoreResultAction { + public: + explicit IgnoreResultAction(const A& action) : action_(action) {} + + template <typename F> + operator Action<F>() const { + // Assert statement belongs here because this is the best place to verify + // conditions on F. It produces the clearest error messages + // in most compilers. + // Impl really belongs in this scope as a local class but can't + // because MSVC produces duplicate symbols in different translation units + // in this case. Until MS fixes that bug we put Impl into the class scope + // and put the typedef both here (for use in assert statement) and + // in the Impl class. But both definitions must be the same. + typedef typename internal::Function<F>::Result Result; + + // Asserts at compile time that F returns void. + CompileAssertTypesEqual<void, Result>(); + + return Action<F>(new Impl<F>(action_)); + } + + private: + template <typename F> + class Impl : public ActionInterface<F> { + public: + typedef typename internal::Function<F>::Result Result; + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + explicit Impl(const A& action) : action_(action) {} + + virtual void Perform(const ArgumentTuple& args) { + // Performs the action and ignores its result. + action_.Perform(args); + } + + private: + // Type OriginalFunction is the same as F except that its return + // type is IgnoredValue. + typedef typename internal::Function<F>::MakeResultIgnoredValue + OriginalFunction; + + const Action<OriginalFunction> action_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + const A action_; + + GTEST_DISALLOW_ASSIGN_(IgnoreResultAction); +}; + +// A ReferenceWrapper<T> object represents a reference to type T, +// which can be either const or not. It can be explicitly converted +// from, and implicitly converted to, a T&. Unlike a reference, +// ReferenceWrapper<T> can be copied and can survive template type +// inference. This is used to support by-reference arguments in the +// InvokeArgument<N>(...) action. The idea was from "reference +// wrappers" in tr1, which we don't have in our source tree yet. +template <typename T> +class ReferenceWrapper { + public: + // Constructs a ReferenceWrapper<T> object from a T&. + explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT + + // Allows a ReferenceWrapper<T> object to be implicitly converted to + // a T&. + operator T&() const { return *pointer_; } + private: + T* pointer_; +}; + +// Allows the expression ByRef(x) to be printed as a reference to x. +template <typename T> +void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) { + T& value = ref; + UniversalPrinter<T&>::Print(value, os); +} + +// Does two actions sequentially. Used for implementing the DoAll(a1, +// a2, ...) action. +template <typename Action1, typename Action2> +class DoBothAction { + public: + DoBothAction(Action1 action1, Action2 action2) + : action1_(action1), action2_(action2) {} + + // This template type conversion operator allows DoAll(a1, ..., a_n) + // to be used in ANY function of compatible type. + template <typename F> + operator Action<F>() const { + return Action<F>(new Impl<F>(action1_, action2_)); + } + + private: + // Implements the DoAll(...) action for a particular function type F. + template <typename F> + class Impl : public ActionInterface<F> { + public: + typedef typename Function<F>::Result Result; + typedef typename Function<F>::ArgumentTuple ArgumentTuple; + typedef typename Function<F>::MakeResultVoid VoidResult; + + Impl(const Action<VoidResult>& action1, const Action<F>& action2) + : action1_(action1), action2_(action2) {} + + virtual Result Perform(const ArgumentTuple& args) { + action1_.Perform(args); + return action2_.Perform(args); + } + + private: + const Action<VoidResult> action1_; + const Action<F> action2_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + Action1 action1_; + Action2 action2_; + + GTEST_DISALLOW_ASSIGN_(DoBothAction); +}; + +} // namespace internal + +// An Unused object can be implicitly constructed from ANY value. +// This is handy when defining actions that ignore some or all of the +// mock function arguments. For example, given +// +// MOCK_METHOD3(Foo, double(const string& label, double x, double y)); +// MOCK_METHOD3(Bar, double(int index, double x, double y)); +// +// instead of +// +// double DistanceToOriginWithLabel(const string& label, double x, double y) { +// return sqrt(x*x + y*y); +// } +// double DistanceToOriginWithIndex(int index, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXEPCT_CALL(mock, Foo("abc", _, _)) +// .WillOnce(Invoke(DistanceToOriginWithLabel)); +// EXEPCT_CALL(mock, Bar(5, _, _)) +// .WillOnce(Invoke(DistanceToOriginWithIndex)); +// +// you could write +// +// // We can declare any uninteresting argument as Unused. +// double DistanceToOrigin(Unused, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); +// EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); +typedef internal::IgnoredValue Unused; + +// This constructor allows us to turn an Action<From> object into an +// Action<To>, as long as To's arguments can be implicitly converted +// to From's and From's return type cann be implicitly converted to +// To's. +template <typename To> +template <typename From> +Action<To>::Action(const Action<From>& from) + : impl_(new internal::ActionAdaptor<To, From>(from)) {} + +// Creates an action that returns 'value'. 'value' is passed by value +// instead of const reference - otherwise Return("string literal") +// will trigger a compiler error about using array as initializer. +template <typename R> +internal::ReturnAction<R> Return(R value) { + return internal::ReturnAction<R>(internal::move(value)); +} + +// Creates an action that returns NULL. +inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() { + return MakePolymorphicAction(internal::ReturnNullAction()); +} + +// Creates an action that returns from a void function. +inline PolymorphicAction<internal::ReturnVoidAction> Return() { + return MakePolymorphicAction(internal::ReturnVoidAction()); +} + +// Creates an action that returns the reference to a variable. +template <typename R> +inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT + return internal::ReturnRefAction<R>(x); +} + +// Creates an action that returns the reference to a copy of the +// argument. The copy is created when the action is constructed and +// lives as long as the action. +template <typename R> +inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) { + return internal::ReturnRefOfCopyAction<R>(x); +} + +// Modifies the parent action (a Return() action) to perform a move of the +// argument instead of a copy. +// Return(ByMove()) actions can only be executed once and will assert this +// invariant. +template <typename R> +internal::ByMoveWrapper<R> ByMove(R x) { + return internal::ByMoveWrapper<R>(internal::move(x)); +} + +// Creates an action that does the default action for the give mock function. +inline internal::DoDefaultAction DoDefault() { + return internal::DoDefaultAction(); +} + +// Creates an action that sets the variable pointed by the N-th +// (0-based) function argument to 'value'. +template <size_t N, typename T> +PolymorphicAction< + internal::SetArgumentPointeeAction< + N, T, internal::IsAProtocolMessage<T>::value> > +SetArgPointee(const T& x) { + return MakePolymorphicAction(internal::SetArgumentPointeeAction< + N, T, internal::IsAProtocolMessage<T>::value>(x)); +} + +#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN) +// This overload allows SetArgPointee() to accept a string literal. +// GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish +// this overload from the templated version and emit a compile error. +template <size_t N> +PolymorphicAction< + internal::SetArgumentPointeeAction<N, const char*, false> > +SetArgPointee(const char* p) { + return MakePolymorphicAction(internal::SetArgumentPointeeAction< + N, const char*, false>(p)); +} + +template <size_t N> +PolymorphicAction< + internal::SetArgumentPointeeAction<N, const wchar_t*, false> > +SetArgPointee(const wchar_t* p) { + return MakePolymorphicAction(internal::SetArgumentPointeeAction< + N, const wchar_t*, false>(p)); +} +#endif + +// The following version is DEPRECATED. +template <size_t N, typename T> +PolymorphicAction< + internal::SetArgumentPointeeAction< + N, T, internal::IsAProtocolMessage<T>::value> > +SetArgumentPointee(const T& x) { + return MakePolymorphicAction(internal::SetArgumentPointeeAction< + N, T, internal::IsAProtocolMessage<T>::value>(x)); +} + +// Creates an action that sets a pointer referent to a given value. +template <typename T1, typename T2> +PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) { + return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val)); +} + +#if !GTEST_OS_WINDOWS_MOBILE + +// Creates an action that sets errno and returns the appropriate error. +template <typename T> +PolymorphicAction<internal::SetErrnoAndReturnAction<T> > +SetErrnoAndReturn(int errval, T result) { + return MakePolymorphicAction( + internal::SetErrnoAndReturnAction<T>(errval, result)); +} + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Various overloads for InvokeWithoutArgs(). + +// Creates an action that invokes 'function_impl' with no argument. +template <typename FunctionImpl> +PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> > +InvokeWithoutArgs(FunctionImpl function_impl) { + return MakePolymorphicAction( + internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl)); +} + +// Creates an action that invokes the given method on the given object +// with no argument. +template <class Class, typename MethodPtr> +PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> > +InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) { + return MakePolymorphicAction( + internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>( + obj_ptr, method_ptr)); +} + +// Creates an action that performs an_action and throws away its +// result. In other words, it changes the return type of an_action to +// void. an_action MUST NOT return void, or the code won't compile. +template <typename A> +inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) { + return internal::IgnoreResultAction<A>(an_action); +} + +// Creates a reference wrapper for the given L-value. If necessary, +// you can explicitly specify the type of the reference. For example, +// suppose 'derived' is an object of type Derived, ByRef(derived) +// would wrap a Derived&. If you want to wrap a const Base& instead, +// where Base is a base class of Derived, just write: +// +// ByRef<const Base>(derived) +template <typename T> +inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT + return internal::ReferenceWrapper<T>(l_value); +} + +} // namespace testing + +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-cardinalities.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-cardinalities.h new file mode 100644 index 00000000000..fc315f92ab5 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-cardinalities.h @@ -0,0 +1,147 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some commonly used cardinalities. More +// cardinalities can be defined by the user implementing the +// CardinalityInterface interface if necessary. + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ + +#include <limits.h> +#include <ostream> // NOLINT +#include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" + +namespace testing { + +// To implement a cardinality Foo, define: +// 1. a class FooCardinality that implements the +// CardinalityInterface interface, and +// 2. a factory function that creates a Cardinality object from a +// const FooCardinality*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Cardinality objects can now be copied like plain values. + +// The implementation of a cardinality. +class CardinalityInterface { + public: + virtual ~CardinalityInterface() {} + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + virtual int ConservativeLowerBound() const { return 0; } + virtual int ConservativeUpperBound() const { return INT_MAX; } + + // Returns true iff call_count calls will satisfy this cardinality. + virtual bool IsSatisfiedByCallCount(int call_count) const = 0; + + // Returns true iff call_count calls will saturate this cardinality. + virtual bool IsSaturatedByCallCount(int call_count) const = 0; + + // Describes self to an ostream. + virtual void DescribeTo(::std::ostream* os) const = 0; +}; + +// A Cardinality is a copyable and IMMUTABLE (except by assignment) +// object that specifies how many times a mock function is expected to +// be called. The implementation of Cardinality is just a linked_ptr +// to const CardinalityInterface, so copying is fairly cheap. +// Don't inherit from Cardinality! +class GTEST_API_ Cardinality { + public: + // Constructs a null cardinality. Needed for storing Cardinality + // objects in STL containers. + Cardinality() {} + + // Constructs a Cardinality from its implementation. + explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); } + int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } + + // Returns true iff call_count calls will satisfy this cardinality. + bool IsSatisfiedByCallCount(int call_count) const { + return impl_->IsSatisfiedByCallCount(call_count); + } + + // Returns true iff call_count calls will saturate this cardinality. + bool IsSaturatedByCallCount(int call_count) const { + return impl_->IsSaturatedByCallCount(call_count); + } + + // Returns true iff call_count calls will over-saturate this + // cardinality, i.e. exceed the maximum number of allowed calls. + bool IsOverSaturatedByCallCount(int call_count) const { + return impl_->IsSaturatedByCallCount(call_count) && + !impl_->IsSatisfiedByCallCount(call_count); + } + + // Describes self to an ostream + void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } + + // Describes the given actual call count to an ostream. + static void DescribeActualCallCountTo(int actual_call_count, + ::std::ostream* os); + + private: + internal::linked_ptr<const CardinalityInterface> impl_; +}; + +// Creates a cardinality that allows at least n calls. +GTEST_API_ Cardinality AtLeast(int n); + +// Creates a cardinality that allows at most n calls. +GTEST_API_ Cardinality AtMost(int n); + +// Creates a cardinality that allows any number of calls. +GTEST_API_ Cardinality AnyNumber(); + +// Creates a cardinality that allows between min and max calls. +GTEST_API_ Cardinality Between(int min, int max); + +// Creates a cardinality that allows exactly n calls. +GTEST_API_ Cardinality Exactly(int n); + +// Creates a cardinality from its implementation. +inline Cardinality MakeCardinality(const CardinalityInterface* c) { + return Cardinality(c); +} + +} // namespace testing + +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-actions.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-actions.h new file mode 100644 index 00000000000..b5a889c0c3a --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-actions.h @@ -0,0 +1,2377 @@ +// This file was GENERATED by a script. DO NOT EDIT BY HAND!!! + +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some commonly used variadic actions. + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ + +#include "gmock/gmock-actions.h" +#include "gmock/internal/gmock-port.h" + +namespace testing { +namespace internal { + +// InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary +// function or method with the unpacked values, where F is a function +// type that takes N arguments. +template <typename Result, typename ArgumentTuple> +class InvokeHelper; + +template <typename R> +class InvokeHelper<R, ::testing::tuple<> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<>&) { + return function(); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<>&) { + return (obj_ptr->*method_ptr)(); + } +}; + +template <typename R, typename A1> +class InvokeHelper<R, ::testing::tuple<A1> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<A1>& args) { + return function(get<0>(args)); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<A1>& args) { + return (obj_ptr->*method_ptr)(get<0>(args)); + } +}; + +template <typename R, typename A1, typename A2> +class InvokeHelper<R, ::testing::tuple<A1, A2> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<A1, A2>& args) { + return function(get<0>(args), get<1>(args)); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<A1, A2>& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args)); + } +}; + +template <typename R, typename A1, typename A2, typename A3> +class InvokeHelper<R, ::testing::tuple<A1, A2, A3> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<A1, A2, A3>& args) { + return function(get<0>(args), get<1>(args), get<2>(args)); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<A1, A2, A3>& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), + get<2>(args)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4> +class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, + A4>& args) { + return function(get<0>(args), get<1>(args), get<2>(args), + get<3>(args)); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<A1, A2, A3, A4>& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), + get<2>(args), get<3>(args)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5> +class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, + A5>& args) { + return function(get<0>(args), get<1>(args), get<2>(args), + get<3>(args), get<4>(args)); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<A1, A2, A3, A4, A5>& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), + get<2>(args), get<3>(args), get<4>(args)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6> +class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, + A6>& args) { + return function(get<0>(args), get<1>(args), get<2>(args), + get<3>(args), get<4>(args), get<5>(args)); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<A1, A2, A3, A4, A5, A6>& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), + get<2>(args), get<3>(args), get<4>(args), get<5>(args)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7> +class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, + A6, A7>& args) { + return function(get<0>(args), get<1>(args), get<2>(args), + get<3>(args), get<4>(args), get<5>(args), get<6>(args)); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<A1, A2, A3, A4, A5, A6, + A7>& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), + get<2>(args), get<3>(args), get<4>(args), get<5>(args), + get<6>(args)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8> +class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, + A6, A7, A8>& args) { + return function(get<0>(args), get<1>(args), get<2>(args), + get<3>(args), get<4>(args), get<5>(args), get<6>(args), + get<7>(args)); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, + A8>& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), + get<2>(args), get<3>(args), get<4>(args), get<5>(args), + get<6>(args), get<7>(args)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8, typename A9> +class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, + A6, A7, A8, A9>& args) { + return function(get<0>(args), get<1>(args), get<2>(args), + get<3>(args), get<4>(args), get<5>(args), get<6>(args), + get<7>(args), get<8>(args)); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, + A9>& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), + get<2>(args), get<3>(args), get<4>(args), get<5>(args), + get<6>(args), get<7>(args), get<8>(args)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8, typename A9, + typename A10> +class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, + A10> > { + public: + template <typename Function> + static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, + A6, A7, A8, A9, A10>& args) { + return function(get<0>(args), get<1>(args), get<2>(args), + get<3>(args), get<4>(args), get<5>(args), get<6>(args), + get<7>(args), get<8>(args), get<9>(args)); + } + + template <class Class, typename MethodPtr> + static R InvokeMethod(Class* obj_ptr, + MethodPtr method_ptr, + const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, + A9, A10>& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), + get<2>(args), get<3>(args), get<4>(args), get<5>(args), + get<6>(args), get<7>(args), get<8>(args), get<9>(args)); + } +}; + +// An INTERNAL macro for extracting the type of a tuple field. It's +// subject to change without notice - DO NOT USE IN USER CODE! +#define GMOCK_FIELD_(Tuple, N) \ + typename ::testing::tuple_element<N, Tuple>::type + +// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::type is the +// type of an n-ary function whose i-th (1-based) argument type is the +// k{i}-th (0-based) field of ArgumentTuple, which must be a tuple +// type, and whose return type is Result. For example, +// SelectArgs<int, ::testing::tuple<bool, char, double, long>, 0, 3>::type +// is int(bool, long). +// +// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::Select(args) +// returns the selected fields (k1, k2, ..., k_n) of args as a tuple. +// For example, +// SelectArgs<int, tuple<bool, char, double>, 2, 0>::Select( +// ::testing::make_tuple(true, 'a', 2.5)) +// returns tuple (2.5, true). +// +// The numbers in list k1, k2, ..., k_n must be >= 0, where n can be +// in the range [0, 10]. Duplicates are allowed and they don't have +// to be in an ascending or descending order. + +template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, + int k4, int k5, int k6, int k7, int k8, int k9, int k10> +class SelectArgs { + public: + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), + GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), + GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7), + GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9), + GMOCK_FIELD_(ArgumentTuple, k10)); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& args) { + return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), + get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args), + get<k8>(args), get<k9>(args), get<k10>(args)); + } +}; + +template <typename Result, typename ArgumentTuple> +class SelectArgs<Result, ArgumentTuple, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> { + public: + typedef Result type(); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& /* args */) { + return SelectedArgs(); + } +}; + +template <typename Result, typename ArgumentTuple, int k1> +class SelectArgs<Result, ArgumentTuple, + k1, -1, -1, -1, -1, -1, -1, -1, -1, -1> { + public: + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1)); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& args) { + return SelectedArgs(get<k1>(args)); + } +}; + +template <typename Result, typename ArgumentTuple, int k1, int k2> +class SelectArgs<Result, ArgumentTuple, + k1, k2, -1, -1, -1, -1, -1, -1, -1, -1> { + public: + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), + GMOCK_FIELD_(ArgumentTuple, k2)); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& args) { + return SelectedArgs(get<k1>(args), get<k2>(args)); + } +}; + +template <typename Result, typename ArgumentTuple, int k1, int k2, int k3> +class SelectArgs<Result, ArgumentTuple, + k1, k2, k3, -1, -1, -1, -1, -1, -1, -1> { + public: + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), + GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3)); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& args) { + return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args)); + } +}; + +template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, + int k4> +class SelectArgs<Result, ArgumentTuple, + k1, k2, k3, k4, -1, -1, -1, -1, -1, -1> { + public: + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), + GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4)); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& args) { + return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), + get<k4>(args)); + } +}; + +template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, + int k4, int k5> +class SelectArgs<Result, ArgumentTuple, + k1, k2, k3, k4, k5, -1, -1, -1, -1, -1> { + public: + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), + GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5)); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& args) { + return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), + get<k4>(args), get<k5>(args)); + } +}; + +template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, + int k4, int k5, int k6> +class SelectArgs<Result, ArgumentTuple, + k1, k2, k3, k4, k5, k6, -1, -1, -1, -1> { + public: + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), + GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), + GMOCK_FIELD_(ArgumentTuple, k6)); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& args) { + return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), + get<k4>(args), get<k5>(args), get<k6>(args)); + } +}; + +template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, + int k4, int k5, int k6, int k7> +class SelectArgs<Result, ArgumentTuple, + k1, k2, k3, k4, k5, k6, k7, -1, -1, -1> { + public: + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), + GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), + GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7)); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& args) { + return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), + get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args)); + } +}; + +template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, + int k4, int k5, int k6, int k7, int k8> +class SelectArgs<Result, ArgumentTuple, + k1, k2, k3, k4, k5, k6, k7, k8, -1, -1> { + public: + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), + GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), + GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7), + GMOCK_FIELD_(ArgumentTuple, k8)); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& args) { + return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), + get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args), + get<k8>(args)); + } +}; + +template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, + int k4, int k5, int k6, int k7, int k8, int k9> +class SelectArgs<Result, ArgumentTuple, + k1, k2, k3, k4, k5, k6, k7, k8, k9, -1> { + public: + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), + GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), + GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7), + GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9)); + typedef typename Function<type>::ArgumentTuple SelectedArgs; + static SelectedArgs Select(const ArgumentTuple& args) { + return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), + get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args), + get<k8>(args), get<k9>(args)); + } +}; + +#undef GMOCK_FIELD_ + +// Implements the WithArgs action. +template <typename InnerAction, int k1 = -1, int k2 = -1, int k3 = -1, + int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, + int k9 = -1, int k10 = -1> +class WithArgsAction { + public: + explicit WithArgsAction(const InnerAction& action) : action_(action) {} + + template <typename F> + operator Action<F>() const { return MakeAction(new Impl<F>(action_)); } + + private: + template <typename F> + class Impl : public ActionInterface<F> { + public: + typedef typename Function<F>::Result Result; + typedef typename Function<F>::ArgumentTuple ArgumentTuple; + + explicit Impl(const InnerAction& action) : action_(action) {} + + virtual Result Perform(const ArgumentTuple& args) { + return action_.Perform(SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4, + k5, k6, k7, k8, k9, k10>::Select(args)); + } + + private: + typedef typename SelectArgs<Result, ArgumentTuple, + k1, k2, k3, k4, k5, k6, k7, k8, k9, k10>::type InnerFunctionType; + + Action<InnerFunctionType> action_; + }; + + const InnerAction action_; + + GTEST_DISALLOW_ASSIGN_(WithArgsAction); +}; + +// A macro from the ACTION* family (defined later in this file) +// defines an action that can be used in a mock function. Typically, +// these actions only care about a subset of the arguments of the mock +// function. For example, if such an action only uses the second +// argument, it can be used in any mock function that takes >= 2 +// arguments where the type of the second argument is compatible. +// +// Therefore, the action implementation must be prepared to take more +// arguments than it needs. The ExcessiveArg type is used to +// represent those excessive arguments. In order to keep the compiler +// error messages tractable, we define it in the testing namespace +// instead of testing::internal. However, this is an INTERNAL TYPE +// and subject to change without notice, so a user MUST NOT USE THIS +// TYPE DIRECTLY. +struct ExcessiveArg {}; + +// A helper class needed for implementing the ACTION* macros. +template <typename Result, class Impl> +class ActionHelper { + public: + static Result Perform(Impl* impl, const ::testing::tuple<>& args) { + return impl->template gmock_PerformImpl<>(args, ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg()); + } + + template <typename A0> + static Result Perform(Impl* impl, const ::testing::tuple<A0>& args) { + return impl->template gmock_PerformImpl<A0>(args, get<0>(args), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg()); + } + + template <typename A0, typename A1> + static Result Perform(Impl* impl, const ::testing::tuple<A0, A1>& args) { + return impl->template gmock_PerformImpl<A0, A1>(args, get<0>(args), + get<1>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg()); + } + + template <typename A0, typename A1, typename A2> + static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2>& args) { + return impl->template gmock_PerformImpl<A0, A1, A2>(args, get<0>(args), + get<1>(args), get<2>(args), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg()); + } + + template <typename A0, typename A1, typename A2, typename A3> + static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, + A3>& args) { + return impl->template gmock_PerformImpl<A0, A1, A2, A3>(args, get<0>(args), + get<1>(args), get<2>(args), get<3>(args), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg()); + } + + template <typename A0, typename A1, typename A2, typename A3, typename A4> + static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, + A4>& args) { + return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4>(args, + get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg()); + } + + template <typename A0, typename A1, typename A2, typename A3, typename A4, + typename A5> + static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, + A5>& args) { + return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5>(args, + get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), + get<5>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg()); + } + + template <typename A0, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6> + static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, + A5, A6>& args) { + return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6>(args, + get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), + get<5>(args), get<6>(args), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg()); + } + + template <typename A0, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7> + static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, + A5, A6, A7>& args) { + return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, + A7>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), + get<4>(args), get<5>(args), get<6>(args), get<7>(args), ExcessiveArg(), + ExcessiveArg()); + } + + template <typename A0, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8> + static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, + A5, A6, A7, A8>& args) { + return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7, + A8>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), + get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args), + ExcessiveArg()); + } + + template <typename A0, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8, typename A9> + static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, + A5, A6, A7, A8, A9>& args) { + return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7, A8, + A9>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), + get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args), + get<9>(args)); + } +}; + +} // namespace internal + +// Various overloads for Invoke(). + +// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes +// the selected arguments of the mock function to an_action and +// performs it. It serves as an adaptor between actions with +// different argument lists. C++ doesn't support default arguments for +// function templates, so we have to overload it. +template <int k1, typename InnerAction> +inline internal::WithArgsAction<InnerAction, k1> +WithArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k1>(action); +} + +template <int k1, int k2, typename InnerAction> +inline internal::WithArgsAction<InnerAction, k1, k2> +WithArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k1, k2>(action); +} + +template <int k1, int k2, int k3, typename InnerAction> +inline internal::WithArgsAction<InnerAction, k1, k2, k3> +WithArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k1, k2, k3>(action); +} + +template <int k1, int k2, int k3, int k4, typename InnerAction> +inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4> +WithArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k1, k2, k3, k4>(action); +} + +template <int k1, int k2, int k3, int k4, int k5, typename InnerAction> +inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5> +WithArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5>(action); +} + +template <int k1, int k2, int k3, int k4, int k5, int k6, typename InnerAction> +inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6> +WithArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6>(action); +} + +template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, + typename InnerAction> +inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7> +WithArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, + k7>(action); +} + +template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, + typename InnerAction> +inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8> +WithArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, + k8>(action); +} + +template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, + int k9, typename InnerAction> +inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8, k9> +WithArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8, + k9>(action); +} + +template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, + int k9, int k10, typename InnerAction> +inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8, + k9, k10> +WithArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8, + k9, k10>(action); +} + +// Creates an action that does actions a1, a2, ..., sequentially in +// each invocation. +template <typename Action1, typename Action2> +inline internal::DoBothAction<Action1, Action2> +DoAll(Action1 a1, Action2 a2) { + return internal::DoBothAction<Action1, Action2>(a1, a2); +} + +template <typename Action1, typename Action2, typename Action3> +inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, + Action3> > +DoAll(Action1 a1, Action2 a2, Action3 a3) { + return DoAll(a1, DoAll(a2, a3)); +} + +template <typename Action1, typename Action2, typename Action3, + typename Action4> +inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, + internal::DoBothAction<Action3, Action4> > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4) { + return DoAll(a1, DoAll(a2, a3, a4)); +} + +template <typename Action1, typename Action2, typename Action3, + typename Action4, typename Action5> +inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, + internal::DoBothAction<Action3, internal::DoBothAction<Action4, + Action5> > > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5) { + return DoAll(a1, DoAll(a2, a3, a4, a5)); +} + +template <typename Action1, typename Action2, typename Action3, + typename Action4, typename Action5, typename Action6> +inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, + internal::DoBothAction<Action3, internal::DoBothAction<Action4, + internal::DoBothAction<Action5, Action6> > > > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6) { + return DoAll(a1, DoAll(a2, a3, a4, a5, a6)); +} + +template <typename Action1, typename Action2, typename Action3, + typename Action4, typename Action5, typename Action6, typename Action7> +inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, + internal::DoBothAction<Action3, internal::DoBothAction<Action4, + internal::DoBothAction<Action5, internal::DoBothAction<Action6, + Action7> > > > > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, + Action7 a7) { + return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7)); +} + +template <typename Action1, typename Action2, typename Action3, + typename Action4, typename Action5, typename Action6, typename Action7, + typename Action8> +inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, + internal::DoBothAction<Action3, internal::DoBothAction<Action4, + internal::DoBothAction<Action5, internal::DoBothAction<Action6, + internal::DoBothAction<Action7, Action8> > > > > > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, + Action7 a7, Action8 a8) { + return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8)); +} + +template <typename Action1, typename Action2, typename Action3, + typename Action4, typename Action5, typename Action6, typename Action7, + typename Action8, typename Action9> +inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, + internal::DoBothAction<Action3, internal::DoBothAction<Action4, + internal::DoBothAction<Action5, internal::DoBothAction<Action6, + internal::DoBothAction<Action7, internal::DoBothAction<Action8, + Action9> > > > > > > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, + Action7 a7, Action8 a8, Action9 a9) { + return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9)); +} + +template <typename Action1, typename Action2, typename Action3, + typename Action4, typename Action5, typename Action6, typename Action7, + typename Action8, typename Action9, typename Action10> +inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, + internal::DoBothAction<Action3, internal::DoBothAction<Action4, + internal::DoBothAction<Action5, internal::DoBothAction<Action6, + internal::DoBothAction<Action7, internal::DoBothAction<Action8, + internal::DoBothAction<Action9, Action10> > > > > > > > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, + Action7 a7, Action8 a8, Action9 a9, Action10 a10) { + return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9, a10)); +} + +} // namespace testing + +// The ACTION* family of macros can be used in a namespace scope to +// define custom actions easily. The syntax: +// +// ACTION(name) { statements; } +// +// will define an action with the given name that executes the +// statements. The value returned by the statements will be used as +// the return value of the action. Inside the statements, you can +// refer to the K-th (0-based) argument of the mock function by +// 'argK', and refer to its type by 'argK_type'. For example: +// +// ACTION(IncrementArg1) { +// arg1_type temp = arg1; +// return ++(*temp); +// } +// +// allows you to write +// +// ...WillOnce(IncrementArg1()); +// +// You can also refer to the entire argument tuple and its type by +// 'args' and 'args_type', and refer to the mock function type and its +// return type by 'function_type' and 'return_type'. +// +// Note that you don't need to specify the types of the mock function +// arguments. However rest assured that your code is still type-safe: +// you'll get a compiler error if *arg1 doesn't support the ++ +// operator, or if the type of ++(*arg1) isn't compatible with the +// mock function's return type, for example. +// +// Sometimes you'll want to parameterize the action. For that you can use +// another macro: +// +// ACTION_P(name, param_name) { statements; } +// +// For example: +// +// ACTION_P(Add, n) { return arg0 + n; } +// +// will allow you to write: +// +// ...WillOnce(Add(5)); +// +// Note that you don't need to provide the type of the parameter +// either. If you need to reference the type of a parameter named +// 'foo', you can write 'foo_type'. For example, in the body of +// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type +// of 'n'. +// +// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support +// multi-parameter actions. +// +// For the purpose of typing, you can view +// +// ACTION_Pk(Foo, p1, ..., pk) { ... } +// +// as shorthand for +// +// template <typename p1_type, ..., typename pk_type> +// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... } +// +// In particular, you can provide the template type arguments +// explicitly when invoking Foo(), as in Foo<long, bool>(5, false); +// although usually you can rely on the compiler to infer the types +// for you automatically. You can assign the result of expression +// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ..., +// pk_type>. This can be useful when composing actions. +// +// You can also overload actions with different numbers of parameters: +// +// ACTION_P(Plus, a) { ... } +// ACTION_P2(Plus, a, b) { ... } +// +// While it's tempting to always use the ACTION* macros when defining +// a new action, you should also consider implementing ActionInterface +// or using MakePolymorphicAction() instead, especially if you need to +// use the action a lot. While these approaches require more work, +// they give you more control on the types of the mock function +// arguments and the action parameters, which in general leads to +// better compiler error messages that pay off in the long run. They +// also allow overloading actions based on parameter types (as opposed +// to just based on the number of parameters). +// +// CAVEAT: +// +// ACTION*() can only be used in a namespace scope. The reason is +// that C++ doesn't yet allow function-local types to be used to +// instantiate templates. The up-coming C++0x standard will fix this. +// Once that's done, we'll consider supporting using ACTION*() inside +// a function. +// +// MORE INFORMATION: +// +// To learn more about using these macros, please search for 'ACTION' +// on http://code.google.com/p/googlemock/wiki/CookBook. + +// An internal macro needed for implementing ACTION*(). +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\ + const args_type& args GTEST_ATTRIBUTE_UNUSED_, \ + arg0_type arg0 GTEST_ATTRIBUTE_UNUSED_, \ + arg1_type arg1 GTEST_ATTRIBUTE_UNUSED_, \ + arg2_type arg2 GTEST_ATTRIBUTE_UNUSED_, \ + arg3_type arg3 GTEST_ATTRIBUTE_UNUSED_, \ + arg4_type arg4 GTEST_ATTRIBUTE_UNUSED_, \ + arg5_type arg5 GTEST_ATTRIBUTE_UNUSED_, \ + arg6_type arg6 GTEST_ATTRIBUTE_UNUSED_, \ + arg7_type arg7 GTEST_ATTRIBUTE_UNUSED_, \ + arg8_type arg8 GTEST_ATTRIBUTE_UNUSED_, \ + arg9_type arg9 GTEST_ATTRIBUTE_UNUSED_ + +// Sometimes you want to give an action explicit template parameters +// that cannot be inferred from its value parameters. ACTION() and +// ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that +// and can be viewed as an extension to ACTION() and ACTION_P*(). +// +// The syntax: +// +// ACTION_TEMPLATE(ActionName, +// HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), +// AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } +// +// defines an action template that takes m explicit template +// parameters and n value parameters. name_i is the name of the i-th +// template parameter, and kind_i specifies whether it's a typename, +// an integral constant, or a template. p_i is the name of the i-th +// value parameter. +// +// Example: +// +// // DuplicateArg<k, T>(output) converts the k-th argument of the mock +// // function to type T and copies it to *output. +// ACTION_TEMPLATE(DuplicateArg, +// HAS_2_TEMPLATE_PARAMS(int, k, typename, T), +// AND_1_VALUE_PARAMS(output)) { +// *output = T(::testing::get<k>(args)); +// } +// ... +// int n; +// EXPECT_CALL(mock, Foo(_, _)) +// .WillOnce(DuplicateArg<1, unsigned char>(&n)); +// +// To create an instance of an action template, write: +// +// ActionName<t1, ..., t_m>(v1, ..., v_n) +// +// where the ts are the template arguments and the vs are the value +// arguments. The value argument types are inferred by the compiler. +// If you want to explicitly specify the value argument types, you can +// provide additional template arguments: +// +// ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) +// +// where u_i is the desired type of v_i. +// +// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the +// number of value parameters, but not on the number of template +// parameters. Without the restriction, the meaning of the following +// is unclear: +// +// OverloadedAction<int, bool>(x); +// +// Are we using a single-template-parameter action where 'bool' refers +// to the type of x, or are we using a two-template-parameter action +// where the compiler is asked to infer the type of x? +// +// Implementation notes: +// +// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and +// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for +// implementing ACTION_TEMPLATE. The main trick we use is to create +// new macro invocations when expanding a macro. For example, we have +// +// #define ACTION_TEMPLATE(name, template_params, value_params) +// ... GMOCK_INTERNAL_DECL_##template_params ... +// +// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...) +// to expand to +// +// ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ... +// +// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the +// preprocessor will continue to expand it to +// +// ... typename T ... +// +// This technique conforms to the C++ standard and is portable. It +// allows us to implement action templates using O(N) code, where N is +// the maximum number of template/value parameters supported. Without +// using it, we'd have to devote O(N^2) amount of code to implement all +// combinations of m and n. + +// Declares the template parameters. +#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0 +#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ + name1) kind0 name0, kind1 name1 +#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2) kind0 name0, kind1 name1, kind2 name2 +#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \ + kind3 name3 +#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \ + kind2 name2, kind3 name3, kind4 name4 +#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \ + kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 +#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ + name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ + kind5 name5, kind6 name6 +#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ + kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \ + kind4 name4, kind5 name5, kind6 name6, kind7 name7 +#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ + kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \ + kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \ + kind8 name8 +#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ + name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ + name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \ + kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \ + kind6 name6, kind7 name7, kind8 name8, kind9 name9 + +// Lists the template parameters. +#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0 +#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ + name1) name0, name1 +#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2) name0, name1, name2 +#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3) name0, name1, name2, name3 +#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \ + name4 +#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \ + name2, name3, name4, name5 +#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ + name6) name0, name1, name2, name3, name4, name5, name6 +#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ + kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7 +#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ + kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ + kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \ + name6, name7, name8 +#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ + name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ + name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \ + name3, name4, name5, name6, name7, name8, name9 + +// Declares the types of value parameters. +#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS() +#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \ + typename p0##_type, typename p1##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \ + typename p0##_type, typename p1##_type, typename p2##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ + typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ + typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ + typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6) , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \ + typename p2##_type, typename p3##_type, typename p4##_type, \ + typename p5##_type, typename p6##_type, typename p7##_type, \ + typename p8##_type, typename p9##_type + +// Initializes the value parameters. +#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\ + () +#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\ + (p0##_type gmock_p0) : p0(gmock_p0) +#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\ + (p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1) +#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\ + (p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) +#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3) +#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), \ + p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) +#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) +#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) +#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), \ + p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ + p7(gmock_p7) +#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7, p8)\ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7, \ + p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ + p8(gmock_p8) +#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7, p8, p9)\ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ + p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ + p8(gmock_p8), p9(gmock_p9) + +// Declares the fields for storing the value parameters. +#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() +#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0; +#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \ + p1##_type p1; +#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \ + p1##_type p1; p2##_type p2; +#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \ + p1##_type p1; p2##_type p2; p3##_type p3; +#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ + p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; +#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ + p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ + p5##_type p5; +#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ + p5##_type p5; p6##_type p6; +#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ + p5##_type p5; p6##_type p6; p7##_type p7; +#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ + p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; +#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ + p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \ + p9##_type p9; + +// Lists the value parameters. +#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS() +#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0 +#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1 +#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2 +#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3 +#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \ + p2, p3, p4 +#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \ + p1, p2, p3, p4, p5 +#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6) p0, p1, p2, p3, p4, p5, p6 +#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7) p0, p1, p2, p3, p4, p5, p6, p7 +#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8 +#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 + +// Lists the value parameter types. +#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS() +#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \ + p1##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \ + p1##_type, p2##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ + p0##_type, p1##_type, p2##_type, p3##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ + p0##_type, p1##_type, p2##_type, p3##_type, p4##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ + p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ + p6##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type, p6##_type, p7##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type, p6##_type, p7##_type, p8##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type, p6##_type, p7##_type, p8##_type, p9##_type + +// Declares the value parameters. +#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS() +#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0 +#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \ + p1##_type p1 +#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \ + p1##_type p1, p2##_type p2 +#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \ + p1##_type p1, p2##_type p2, p3##_type p3 +#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ + p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 +#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ + p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5 +#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ + p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5, p6##_type p6 +#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5, p6##_type p6, p7##_type p7 +#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ + p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 +#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ + p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ + p9##_type p9 + +// The suffix of the class template implementing the action template. +#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS() +#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P +#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2 +#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3 +#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4 +#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5 +#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6 +#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7 +#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7) P8 +#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7, p8) P9 +#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ + p7, p8, p9) P10 + +// The name of the class template implementing the action template. +#define GMOCK_ACTION_CLASS_(name, value_params)\ + GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) + +#define ACTION_TEMPLATE(name, template_params, value_params)\ + template <GMOCK_INTERNAL_DECL_##template_params\ + GMOCK_INTERNAL_DECL_TYPE_##value_params>\ + class GMOCK_ACTION_CLASS_(name, value_params) {\ + public:\ + explicit GMOCK_ACTION_CLASS_(name, value_params)\ + GMOCK_INTERNAL_INIT_##value_params {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + GMOCK_INTERNAL_DEFN_##value_params\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(\ + new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\ + }\ + GMOCK_INTERNAL_DEFN_##value_params\ + private:\ + GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\ + };\ + template <GMOCK_INTERNAL_DECL_##template_params\ + GMOCK_INTERNAL_DECL_TYPE_##value_params>\ + inline GMOCK_ACTION_CLASS_(name, value_params)<\ + GMOCK_INTERNAL_LIST_##template_params\ + GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\ + GMOCK_INTERNAL_DECL_##value_params) {\ + return GMOCK_ACTION_CLASS_(name, value_params)<\ + GMOCK_INTERNAL_LIST_##template_params\ + GMOCK_INTERNAL_LIST_TYPE_##value_params>(\ + GMOCK_INTERNAL_LIST_##value_params);\ + }\ + template <GMOCK_INTERNAL_DECL_##template_params\ + GMOCK_INTERNAL_DECL_TYPE_##value_params>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + GMOCK_ACTION_CLASS_(name, value_params)<\ + GMOCK_INTERNAL_LIST_##template_params\ + GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl<F>::\ + gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION(name)\ + class name##Action {\ + public:\ + name##Action() {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + gmock_Impl() {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>());\ + }\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##Action);\ + };\ + inline name##Action name() {\ + return name##Action();\ + }\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##Action::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P(name, p0)\ + template <typename p0##_type>\ + class name##ActionP {\ + public:\ + explicit name##ActionP(p0##_type gmock_p0) : p0(gmock_p0) {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + explicit gmock_Impl(p0##_type gmock_p0) : p0(gmock_p0) {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + p0##_type p0;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>(p0));\ + }\ + p0##_type p0;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##ActionP);\ + };\ + template <typename p0##_type>\ + inline name##ActionP<p0##_type> name(p0##_type p0) {\ + return name##ActionP<p0##_type>(p0);\ + }\ + template <typename p0##_type>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##ActionP<p0##_type>::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P2(name, p0, p1)\ + template <typename p0##_type, typename p1##_type>\ + class name##ActionP2 {\ + public:\ + name##ActionP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ + p1(gmock_p1) {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ + p1(gmock_p1) {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + p0##_type p0;\ + p1##_type p1;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>(p0, p1));\ + }\ + p0##_type p0;\ + p1##_type p1;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##ActionP2);\ + };\ + template <typename p0##_type, typename p1##_type>\ + inline name##ActionP2<p0##_type, p1##_type> name(p0##_type p0, \ + p1##_type p1) {\ + return name##ActionP2<p0##_type, p1##_type>(p0, p1);\ + }\ + template <typename p0##_type, typename p1##_type>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##ActionP2<p0##_type, p1##_type>::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P3(name, p0, p1, p2)\ + template <typename p0##_type, typename p1##_type, typename p2##_type>\ + class name##ActionP3 {\ + public:\ + name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2));\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##ActionP3);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type>\ + inline name##ActionP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \ + p1##_type p1, p2##_type p2) {\ + return name##ActionP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##ActionP3<p0##_type, p1##_type, \ + p2##_type>::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P4(name, p0, p1, p2, p3)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type>\ + class name##ActionP4 {\ + public:\ + name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \ + p2(gmock_p2), p3(gmock_p3) {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3) {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3));\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##ActionP4);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type>\ + inline name##ActionP4<p0##_type, p1##_type, p2##_type, \ + p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \ + p3##_type p3) {\ + return name##ActionP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, p1, \ + p2, p3);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##ActionP4<p0##_type, p1##_type, p2##_type, \ + p3##_type>::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P5(name, p0, p1, p2, p3, p4)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type>\ + class name##ActionP5 {\ + public:\ + name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, \ + p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4) {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), \ + p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4));\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##ActionP5);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type>\ + inline name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ + p4##_type p4) {\ + return name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type>(p0, p1, p2, p3, p4);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type>::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P6(name, p0, p1, p2, p3, p4, p5)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type>\ + class name##ActionP6 {\ + public:\ + name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5));\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##ActionP6);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type>\ + inline name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \ + p3##_type p3, p4##_type p4, p5##_type p5) {\ + return name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type>::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P7(name, p0, p1, p2, p3, p4, p5, p6)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type>\ + class name##ActionP7 {\ + public:\ + name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \ + p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \ + p6(gmock_p6) {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \ + p6));\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##ActionP7);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type>\ + inline name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \ + p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ + p6##_type p6) {\ + return name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type, p6##_type>::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P8(name, p0, p1, p2, p3, p4, p5, p6, p7)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type>\ + class name##ActionP8 {\ + public:\ + name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, \ + p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ + p7(gmock_p7) {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), \ + p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), \ + p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \ + p6, p7));\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##ActionP8);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type>\ + inline name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \ + p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ + p6##_type p6, p7##_type p7) {\ + return name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \ + p6, p7);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type, p6##_type, \ + p7##_type>::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type>\ + class name##ActionP9 {\ + public:\ + name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ + p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ + p8(gmock_p8) {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7, \ + p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ + p7(gmock_p7), p8(gmock_p8) {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + p8##_type p8;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \ + p6, p7, p8));\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + p8##_type p8;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##ActionP9);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type>\ + inline name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, \ + p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ + p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ + p8##_type p8) {\ + return name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \ + p3, p4, p5, p6, p7, p8);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type, p6##_type, p7##_type, \ + p8##_type>::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type, \ + typename p9##_type>\ + class name##ActionP10 {\ + public:\ + name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ + p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \ + p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ + p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\ + template <typename F>\ + class gmock_Impl : public ::testing::ActionInterface<F> {\ + public:\ + typedef F function_type;\ + typedef typename ::testing::internal::Function<F>::Result return_type;\ + typedef typename ::testing::internal::Function<F>::ArgumentTuple\ + args_type;\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ + p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ + p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\ + virtual return_type Perform(const args_type& args) {\ + return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ + Perform(this, args);\ + }\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ + arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ + arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ + arg9_type arg9) const;\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + p8##_type p8;\ + p9##_type p9;\ + private:\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename F> operator ::testing::Action<F>() const {\ + return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \ + p6, p7, p8, p9));\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + p8##_type p8;\ + p9##_type p9;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##ActionP10);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type, \ + typename p9##_type>\ + inline name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ + p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ + p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ + p9##_type p9) {\ + return name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \ + p1, p2, p3, p4, p5, p6, p7, p8, p9);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type, \ + typename p9##_type>\ + template <typename F>\ + template <typename arg0_type, typename arg1_type, typename arg2_type, \ + typename arg3_type, typename arg4_type, typename arg5_type, \ + typename arg6_type, typename arg7_type, typename arg8_type, \ + typename arg9_type>\ + typename ::testing::internal::Function<F>::Result\ + name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type, p6##_type, p7##_type, p8##_type, \ + p9##_type>::gmock_Impl<F>::gmock_PerformImpl(\ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +namespace testing { + + +// The ACTION*() macros trigger warning C4100 (unreferenced formal +// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in +// the macro definition, as the warnings are generated when the macro +// is expanded and macro expansion cannot contain #pragma. Therefore +// we suppress them here. +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4100) +#endif + +// Various overloads for InvokeArgument<N>(). +// +// The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th +// (0-based) argument, which must be a k-ary callable, of the mock +// function, with arguments a1, a2, ..., a_k. +// +// Notes: +// +// 1. The arguments are passed by value by default. If you need to +// pass an argument by reference, wrap it inside ByRef(). For +// example, +// +// InvokeArgument<1>(5, string("Hello"), ByRef(foo)) +// +// passes 5 and string("Hello") by value, and passes foo by +// reference. +// +// 2. If the callable takes an argument by reference but ByRef() is +// not used, it will receive the reference to a copy of the value, +// instead of the original value. For example, when the 0-th +// argument of the mock function takes a const string&, the action +// +// InvokeArgument<0>(string("Hello")) +// +// makes a copy of the temporary string("Hello") object and passes a +// reference of the copy, instead of the original temporary object, +// to the callable. This makes it easy for a user to define an +// InvokeArgument action from temporary values and have it performed +// later. + +namespace internal { +namespace invoke_argument { + +// Appears in InvokeArgumentAdl's argument list to help avoid +// accidental calls to user functions of the same name. +struct AdlTag {}; + +// InvokeArgumentAdl - a helper for InvokeArgument. +// The basic overloads are provided here for generic functors. +// Overloads for other custom-callables are provided in the +// internal/custom/callback-actions.h header. + +template <typename R, typename F> +R InvokeArgumentAdl(AdlTag, F f) { + return f(); +} +template <typename R, typename F, typename A1> +R InvokeArgumentAdl(AdlTag, F f, A1 a1) { + return f(a1); +} +template <typename R, typename F, typename A1, typename A2> +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) { + return f(a1, a2); +} +template <typename R, typename F, typename A1, typename A2, typename A3> +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) { + return f(a1, a2, a3); +} +template <typename R, typename F, typename A1, typename A2, typename A3, + typename A4> +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) { + return f(a1, a2, a3, a4); +} +template <typename R, typename F, typename A1, typename A2, typename A3, + typename A4, typename A5> +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { + return f(a1, a2, a3, a4, a5); +} +template <typename R, typename F, typename A1, typename A2, typename A3, + typename A4, typename A5, typename A6> +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { + return f(a1, a2, a3, a4, a5, a6); +} +template <typename R, typename F, typename A1, typename A2, typename A3, + typename A4, typename A5, typename A6, typename A7> +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, + A7 a7) { + return f(a1, a2, a3, a4, a5, a6, a7); +} +template <typename R, typename F, typename A1, typename A2, typename A3, + typename A4, typename A5, typename A6, typename A7, typename A8> +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, + A7 a7, A8 a8) { + return f(a1, a2, a3, a4, a5, a6, a7, a8); +} +template <typename R, typename F, typename A1, typename A2, typename A3, + typename A4, typename A5, typename A6, typename A7, typename A8, + typename A9> +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, + A7 a7, A8 a8, A9 a9) { + return f(a1, a2, a3, a4, a5, a6, a7, a8, a9); +} +template <typename R, typename F, typename A1, typename A2, typename A3, + typename A4, typename A5, typename A6, typename A7, typename A8, + typename A9, typename A10> +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, + A7 a7, A8 a8, A9 a9, A10 a10) { + return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); +} +} // namespace invoke_argument +} // namespace internal + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_0_VALUE_PARAMS()) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args)); +} + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_1_VALUE_PARAMS(p0)) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args), p0); +} + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_2_VALUE_PARAMS(p0, p1)) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args), p0, p1); +} + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_3_VALUE_PARAMS(p0, p1, p2)) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args), p0, p1, p2); +} + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args), p0, p1, p2, p3); +} + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args), p0, p1, p2, p3, p4); +} + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args), p0, p1, p2, p3, p4, p5); +} + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6); +} + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7); +} + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8); +} + +ACTION_TEMPLATE(InvokeArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { + using internal::invoke_argument::InvokeArgumentAdl; + return InvokeArgumentAdl<return_type>( + internal::invoke_argument::AdlTag(), + ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); +} + +// Various overloads for ReturnNew<T>(). +// +// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new +// instance of type T, constructed on the heap with constructor arguments +// a1, a2, ..., and a_k. The caller assumes ownership of the returned value. +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_0_VALUE_PARAMS()) { + return new T(); +} + +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_1_VALUE_PARAMS(p0)) { + return new T(p0); +} + +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_2_VALUE_PARAMS(p0, p1)) { + return new T(p0, p1); +} + +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_3_VALUE_PARAMS(p0, p1, p2)) { + return new T(p0, p1, p2); +} + +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { + return new T(p0, p1, p2, p3); +} + +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { + return new T(p0, p1, p2, p3, p4); +} + +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { + return new T(p0, p1, p2, p3, p4, p5); +} + +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { + return new T(p0, p1, p2, p3, p4, p5, p6); +} + +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { + return new T(p0, p1, p2, p3, p4, p5, p6, p7); +} + +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { + return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8); +} + +ACTION_TEMPLATE(ReturnNew, + HAS_1_TEMPLATE_PARAMS(typename, T), + AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { + return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); +} + +#ifdef _MSC_VER +# pragma warning(pop) +#endif + +} // namespace testing + +// Include any custom actions added by the local installation. +// We must include this header at the end to make sure it can use the +// declarations from this file. +#include "gmock/internal/custom/gmock-generated-actions.h" + +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-function-mockers.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-function-mockers.h new file mode 100644 index 00000000000..4fa5ca94849 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-function-mockers.h @@ -0,0 +1,1095 @@ +// This file was GENERATED by command: +// pump.py gmock-generated-function-mockers.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements function mockers of various arities. + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ + +#include "gmock/gmock-spec-builders.h" +#include "gmock/internal/gmock-internal-utils.h" + +#if GTEST_HAS_STD_FUNCTION_ +# include <functional> +#endif + +namespace testing { +namespace internal { + +template <typename F> +class FunctionMockerBase; + +// Note: class FunctionMocker really belongs to the ::testing +// namespace. However if we define it in ::testing, MSVC will +// complain when classes in ::testing::internal declare it as a +// friend class template. To workaround this compiler bug, we define +// FunctionMocker in ::testing::internal and import it into ::testing. +template <typename F> +class FunctionMocker; + +template <typename R> +class FunctionMocker<R()> : public + internal::FunctionMockerBase<R()> { + public: + typedef R F(); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With() { + return this->current_spec(); + } + + R Invoke() { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple()); + } +}; + +template <typename R, typename A1> +class FunctionMocker<R(A1)> : public + internal::FunctionMockerBase<R(A1)> { + public: + typedef R F(A1); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With(const Matcher<A1>& m1) { + this->current_spec().SetMatchers(::testing::make_tuple(m1)); + return this->current_spec(); + } + + R Invoke(A1 a1) { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple(a1)); + } +}; + +template <typename R, typename A1, typename A2> +class FunctionMocker<R(A1, A2)> : public + internal::FunctionMockerBase<R(A1, A2)> { + public: + typedef R F(A1, A2); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2)); + return this->current_spec(); + } + + R Invoke(A1 a1, A2 a2) { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple(a1, a2)); + } +}; + +template <typename R, typename A1, typename A2, typename A3> +class FunctionMocker<R(A1, A2, A3)> : public + internal::FunctionMockerBase<R(A1, A2, A3)> { + public: + typedef R F(A1, A2, A3); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + const Matcher<A3>& m3) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3)); + return this->current_spec(); + } + + R Invoke(A1 a1, A2 a2, A3 a3) { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple(a1, a2, a3)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4> +class FunctionMocker<R(A1, A2, A3, A4)> : public + internal::FunctionMockerBase<R(A1, A2, A3, A4)> { + public: + typedef R F(A1, A2, A3, A4); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + const Matcher<A3>& m3, const Matcher<A4>& m4) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4)); + return this->current_spec(); + } + + R Invoke(A1 a1, A2 a2, A3 a3, A4 a4) { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5> +class FunctionMocker<R(A1, A2, A3, A4, A5)> : public + internal::FunctionMockerBase<R(A1, A2, A3, A4, A5)> { + public: + typedef R F(A1, A2, A3, A4, A5); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5)); + return this->current_spec(); + } + + R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6> +class FunctionMocker<R(A1, A2, A3, A4, A5, A6)> : public + internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6)> { + public: + typedef R F(A1, A2, A3, A4, A5, A6); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, + const Matcher<A6>& m6) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, + m6)); + return this->current_spec(); + } + + R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7> +class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7)> : public + internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7)> { + public: + typedef R F(A1, A2, A3, A4, A5, A6, A7); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, + const Matcher<A6>& m6, const Matcher<A7>& m7) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, + m6, m7)); + return this->current_spec(); + } + + R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8> +class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8)> : public + internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8)> { + public: + typedef R F(A1, A2, A3, A4, A5, A6, A7, A8); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, + const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, + m6, m7, m8)); + return this->current_spec(); + } + + R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8, typename A9> +class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> : public + internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> { + public: + typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, + const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8, + const Matcher<A9>& m9) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, + m6, m7, m8, m9)); + return this->current_spec(); + } + + R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9)); + } +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8, typename A9, + typename A10> +class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> : public + internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> { + public: + typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + + MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, + const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8, + const Matcher<A9>& m9, const Matcher<A10>& m10) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, + m6, m7, m8, m9, m10)); + return this->current_spec(); + } + + R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9, + A10 a10) { + // Even though gcc and MSVC don't enforce it, 'this->' is required + // by the C++ standard [14.6.4] here, as the base class type is + // dependent on the template argument (and thus shouldn't be + // looked into when resolving InvokeWith). + return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9, + a10)); + } +}; + +} // namespace internal + +// The style guide prohibits "using" statements in a namespace scope +// inside a header file. However, the FunctionMocker class template +// is meant to be defined in the ::testing namespace. The following +// line is just a trick for working around a bug in MSVC 8.0, which +// cannot handle it if we define FunctionMocker in ::testing. +using internal::FunctionMocker; + +// GMOCK_RESULT_(tn, F) expands to the result type of function type F. +// We define this as a variadic macro in case F contains unprotected +// commas (the same reason that we use variadic macros in other places +// in this file). +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_RESULT_(tn, ...) \ + tn ::testing::internal::Function<__VA_ARGS__>::Result + +// The type of argument N of the given function type. +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_ARG_(tn, N, ...) \ + tn ::testing::internal::Function<__VA_ARGS__>::Argument##N + +// The matcher type for argument N of the given function type. +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_MATCHER_(tn, N, ...) \ + const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>& + +// The variable for mocking the given method. +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_MOCKER_(arity, constness, Method) \ + GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + ) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 0), \ + this_method_does_not_take_0_arguments); \ + GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(0, constness, Method).Invoke(); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method() constness { \ + GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(0, constness, Method).With(); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \ + Method) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 1), \ + this_method_does_not_take_1_argument); \ + GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(1, constness, Method).Invoke(gmock_a1); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ + GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \ + Method) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 2), \ + this_method_does_not_take_2_arguments); \ + GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(2, constness, Method).Invoke(gmock_a1, gmock_a2); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ + GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \ + Method) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 3), \ + this_method_does_not_take_3_arguments); \ + GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(3, constness, Method).Invoke(gmock_a1, gmock_a2, \ + gmock_a3); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ + GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \ + gmock_a3); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \ + Method) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 4), \ + this_method_does_not_take_4_arguments); \ + GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(4, constness, Method).Invoke(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ + GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \ + Method) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 5), \ + this_method_does_not_take_5_arguments); \ + GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(5, constness, Method).Invoke(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ + GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \ + Method) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ + GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 6), \ + this_method_does_not_take_6_arguments); \ + GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(6, constness, Method).Invoke(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ + GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ + GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \ + Method) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ + GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 7), \ + this_method_does_not_take_7_arguments); \ + GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(7, constness, Method).Invoke(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ + GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ + GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \ + Method) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ + GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ + GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 8), \ + this_method_does_not_take_8_arguments); \ + GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(8, constness, Method).Invoke(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ + GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ + GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ + GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \ + Method) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ + GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ + GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \ + GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 9), \ + this_method_does_not_take_9_arguments); \ + GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(9, constness, Method).Invoke(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \ + gmock_a9); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ + GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ + GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ + GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ + GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \ + gmock_a9); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \ + Method) + +// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! +#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ + GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ + GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \ + GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \ + GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \ + GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ + == 10), \ + this_method_does_not_take_10_arguments); \ + GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(10, constness, Method).Invoke(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \ + gmock_a10); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& \ + gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ + GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ + GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ + GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \ + GMOCK_MATCHER_(tn, 10, \ + __VA_ARGS__) gmock_a10) constness { \ + GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \ + gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \ + gmock_a10); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \ + Method) + +#define MOCK_METHOD0(m, ...) GMOCK_METHOD0_(, , , m, __VA_ARGS__) +#define MOCK_METHOD1(m, ...) GMOCK_METHOD1_(, , , m, __VA_ARGS__) +#define MOCK_METHOD2(m, ...) GMOCK_METHOD2_(, , , m, __VA_ARGS__) +#define MOCK_METHOD3(m, ...) GMOCK_METHOD3_(, , , m, __VA_ARGS__) +#define MOCK_METHOD4(m, ...) GMOCK_METHOD4_(, , , m, __VA_ARGS__) +#define MOCK_METHOD5(m, ...) GMOCK_METHOD5_(, , , m, __VA_ARGS__) +#define MOCK_METHOD6(m, ...) GMOCK_METHOD6_(, , , m, __VA_ARGS__) +#define MOCK_METHOD7(m, ...) GMOCK_METHOD7_(, , , m, __VA_ARGS__) +#define MOCK_METHOD8(m, ...) GMOCK_METHOD8_(, , , m, __VA_ARGS__) +#define MOCK_METHOD9(m, ...) GMOCK_METHOD9_(, , , m, __VA_ARGS__) +#define MOCK_METHOD10(m, ...) GMOCK_METHOD10_(, , , m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0(m, ...) GMOCK_METHOD0_(, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD1(m, ...) GMOCK_METHOD1_(, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD2(m, ...) GMOCK_METHOD2_(, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD3(m, ...) GMOCK_METHOD3_(, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD4(m, ...) GMOCK_METHOD4_(, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD5(m, ...) GMOCK_METHOD5_(, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD6(m, ...) GMOCK_METHOD6_(, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD7(m, ...) GMOCK_METHOD7_(, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD8(m, ...) GMOCK_METHOD8_(, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD9(m, ...) GMOCK_METHOD9_(, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD10(m, ...) GMOCK_METHOD10_(, const, , m, __VA_ARGS__) + +#define MOCK_METHOD0_T(m, ...) GMOCK_METHOD0_(typename, , , m, __VA_ARGS__) +#define MOCK_METHOD1_T(m, ...) GMOCK_METHOD1_(typename, , , m, __VA_ARGS__) +#define MOCK_METHOD2_T(m, ...) GMOCK_METHOD2_(typename, , , m, __VA_ARGS__) +#define MOCK_METHOD3_T(m, ...) GMOCK_METHOD3_(typename, , , m, __VA_ARGS__) +#define MOCK_METHOD4_T(m, ...) GMOCK_METHOD4_(typename, , , m, __VA_ARGS__) +#define MOCK_METHOD5_T(m, ...) GMOCK_METHOD5_(typename, , , m, __VA_ARGS__) +#define MOCK_METHOD6_T(m, ...) GMOCK_METHOD6_(typename, , , m, __VA_ARGS__) +#define MOCK_METHOD7_T(m, ...) GMOCK_METHOD7_(typename, , , m, __VA_ARGS__) +#define MOCK_METHOD8_T(m, ...) GMOCK_METHOD8_(typename, , , m, __VA_ARGS__) +#define MOCK_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, , , m, __VA_ARGS__) +#define MOCK_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, , , m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T(m, ...) \ + GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T(m, ...) \ + GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T(m, ...) \ + GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T(m, ...) \ + GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T(m, ...) \ + GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T(m, ...) \ + GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T(m, ...) \ + GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T(m, ...) \ + GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T(m, ...) \ + GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T(m, ...) \ + GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T(m, ...) \ + GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__) + +#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD0_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD1_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD2_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD3_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD4_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD5_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD6_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD7_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD8_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD9_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD10_(, , ct, m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__) + +#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__) + +// A MockFunction<F> class has one mock method whose type is F. It is +// useful when you just want your test code to emit some messages and +// have Google Mock verify the right messages are sent (and perhaps at +// the right times). For example, if you are exercising code: +// +// Foo(1); +// Foo(2); +// Foo(3); +// +// and want to verify that Foo(1) and Foo(3) both invoke +// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write: +// +// TEST(FooTest, InvokesBarCorrectly) { +// MyMock mock; +// MockFunction<void(string check_point_name)> check; +// { +// InSequence s; +// +// EXPECT_CALL(mock, Bar("a")); +// EXPECT_CALL(check, Call("1")); +// EXPECT_CALL(check, Call("2")); +// EXPECT_CALL(mock, Bar("a")); +// } +// Foo(1); +// check.Call("1"); +// Foo(2); +// check.Call("2"); +// Foo(3); +// } +// +// The expectation spec says that the first Bar("a") must happen +// before check point "1", the second Bar("a") must happen after check +// point "2", and nothing should happen between the two check +// points. The explicit check points make it easy to tell which +// Bar("a") is called by which call to Foo(). +// +// MockFunction<F> can also be used to exercise code that accepts +// std::function<F> callbacks. To do so, use AsStdFunction() method +// to create std::function proxy forwarding to original object's Call. +// Example: +// +// TEST(FooTest, RunsCallbackWithBarArgument) { +// MockFunction<int(string)> callback; +// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1)); +// Foo(callback.AsStdFunction()); +// } +template <typename F> +class MockFunction; + +template <typename R> +class MockFunction<R()> { + public: + MockFunction() {} + + MOCK_METHOD0_T(Call, R()); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R()> AsStdFunction() { + return [this]() -> R { + return this->Call(); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +template <typename R, typename A0> +class MockFunction<R(A0)> { + public: + MockFunction() {} + + MOCK_METHOD1_T(Call, R(A0)); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R(A0)> AsStdFunction() { + return [this](A0 a0) -> R { + return this->Call(a0); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +template <typename R, typename A0, typename A1> +class MockFunction<R(A0, A1)> { + public: + MockFunction() {} + + MOCK_METHOD2_T(Call, R(A0, A1)); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R(A0, A1)> AsStdFunction() { + return [this](A0 a0, A1 a1) -> R { + return this->Call(a0, a1); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +template <typename R, typename A0, typename A1, typename A2> +class MockFunction<R(A0, A1, A2)> { + public: + MockFunction() {} + + MOCK_METHOD3_T(Call, R(A0, A1, A2)); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R(A0, A1, A2)> AsStdFunction() { + return [this](A0 a0, A1 a1, A2 a2) -> R { + return this->Call(a0, a1, a2); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +template <typename R, typename A0, typename A1, typename A2, typename A3> +class MockFunction<R(A0, A1, A2, A3)> { + public: + MockFunction() {} + + MOCK_METHOD4_T(Call, R(A0, A1, A2, A3)); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R(A0, A1, A2, A3)> AsStdFunction() { + return [this](A0 a0, A1 a1, A2 a2, A3 a3) -> R { + return this->Call(a0, a1, a2, a3); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +template <typename R, typename A0, typename A1, typename A2, typename A3, + typename A4> +class MockFunction<R(A0, A1, A2, A3, A4)> { + public: + MockFunction() {} + + MOCK_METHOD5_T(Call, R(A0, A1, A2, A3, A4)); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R(A0, A1, A2, A3, A4)> AsStdFunction() { + return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) -> R { + return this->Call(a0, a1, a2, a3, a4); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +template <typename R, typename A0, typename A1, typename A2, typename A3, + typename A4, typename A5> +class MockFunction<R(A0, A1, A2, A3, A4, A5)> { + public: + MockFunction() {} + + MOCK_METHOD6_T(Call, R(A0, A1, A2, A3, A4, A5)); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R(A0, A1, A2, A3, A4, A5)> AsStdFunction() { + return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) -> R { + return this->Call(a0, a1, a2, a3, a4, a5); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +template <typename R, typename A0, typename A1, typename A2, typename A3, + typename A4, typename A5, typename A6> +class MockFunction<R(A0, A1, A2, A3, A4, A5, A6)> { + public: + MockFunction() {} + + MOCK_METHOD7_T(Call, R(A0, A1, A2, A3, A4, A5, A6)); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R(A0, A1, A2, A3, A4, A5, A6)> AsStdFunction() { + return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) -> R { + return this->Call(a0, a1, a2, a3, a4, a5, a6); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +template <typename R, typename A0, typename A1, typename A2, typename A3, + typename A4, typename A5, typename A6, typename A7> +class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7)> { + public: + MockFunction() {} + + MOCK_METHOD8_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7)); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R(A0, A1, A2, A3, A4, A5, A6, A7)> AsStdFunction() { + return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) -> R { + return this->Call(a0, a1, a2, a3, a4, a5, a6, a7); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +template <typename R, typename A0, typename A1, typename A2, typename A3, + typename A4, typename A5, typename A6, typename A7, typename A8> +class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> { + public: + MockFunction() {} + + MOCK_METHOD9_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7, A8)); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> AsStdFunction() { + return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, + A8 a8) -> R { + return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +template <typename R, typename A0, typename A1, typename A2, typename A3, + typename A4, typename A5, typename A6, typename A7, typename A8, + typename A9> +class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> { + public: + MockFunction() {} + + MOCK_METHOD10_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)); + +#if GTEST_HAS_STD_FUNCTION_ + std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> AsStdFunction() { + return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, + A8 a8, A9 a9) -> R { + return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); + }; + } +#endif // GTEST_HAS_STD_FUNCTION_ + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); +}; + +} // namespace testing + +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-matchers.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-matchers.h new file mode 100644 index 00000000000..57056fd91d2 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-matchers.h @@ -0,0 +1,2179 @@ +// This file was GENERATED by command: +// pump.py gmock-generated-matchers.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some commonly used variadic matchers. + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ + +#include <iterator> +#include <sstream> +#include <string> +#include <vector> +#include "gmock/gmock-matchers.h" + +namespace testing { +namespace internal { + +// The type of the i-th (0-based) field of Tuple. +#define GMOCK_FIELD_TYPE_(Tuple, i) \ + typename ::testing::tuple_element<i, Tuple>::type + +// TupleFields<Tuple, k0, ..., kn> is for selecting fields from a +// tuple of type Tuple. It has two members: +// +// type: a tuple type whose i-th field is the ki-th field of Tuple. +// GetSelectedFields(t): returns fields k0, ..., and kn of t as a tuple. +// +// For example, in class TupleFields<tuple<bool, char, int>, 2, 0>, we have: +// +// type is tuple<int, bool>, and +// GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true). + +template <class Tuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1, + int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, + int k9 = -1> +class TupleFields; + +// This generic version is used when there are 10 selectors. +template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, + int k7, int k8, int k9> +class TupleFields { + public: + typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), + GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), + GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), + GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), + GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8), + GMOCK_FIELD_TYPE_(Tuple, k9)> type; + static type GetSelectedFields(const Tuple& t) { + return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), + get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t), get<k9>(t)); + } +}; + +// The following specialization is used for 0 ~ 9 selectors. + +template <class Tuple> +class TupleFields<Tuple, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> { + public: + typedef ::testing::tuple<> type; + static type GetSelectedFields(const Tuple& /* t */) { + return type(); + } +}; + +template <class Tuple, int k0> +class TupleFields<Tuple, k0, -1, -1, -1, -1, -1, -1, -1, -1, -1> { + public: + typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0)> type; + static type GetSelectedFields(const Tuple& t) { + return type(get<k0>(t)); + } +}; + +template <class Tuple, int k0, int k1> +class TupleFields<Tuple, k0, k1, -1, -1, -1, -1, -1, -1, -1, -1> { + public: + typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), + GMOCK_FIELD_TYPE_(Tuple, k1)> type; + static type GetSelectedFields(const Tuple& t) { + return type(get<k0>(t), get<k1>(t)); + } +}; + +template <class Tuple, int k0, int k1, int k2> +class TupleFields<Tuple, k0, k1, k2, -1, -1, -1, -1, -1, -1, -1> { + public: + typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), + GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2)> type; + static type GetSelectedFields(const Tuple& t) { + return type(get<k0>(t), get<k1>(t), get<k2>(t)); + } +}; + +template <class Tuple, int k0, int k1, int k2, int k3> +class TupleFields<Tuple, k0, k1, k2, k3, -1, -1, -1, -1, -1, -1> { + public: + typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), + GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), + GMOCK_FIELD_TYPE_(Tuple, k3)> type; + static type GetSelectedFields(const Tuple& t) { + return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t)); + } +}; + +template <class Tuple, int k0, int k1, int k2, int k3, int k4> +class TupleFields<Tuple, k0, k1, k2, k3, k4, -1, -1, -1, -1, -1> { + public: + typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), + GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), + GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4)> type; + static type GetSelectedFields(const Tuple& t) { + return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t)); + } +}; + +template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5> +class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, -1, -1, -1, -1> { + public: + typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), + GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), + GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), + GMOCK_FIELD_TYPE_(Tuple, k5)> type; + static type GetSelectedFields(const Tuple& t) { + return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), + get<k5>(t)); + } +}; + +template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6> +class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, -1, -1, -1> { + public: + typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), + GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), + GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), + GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6)> type; + static type GetSelectedFields(const Tuple& t) { + return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), + get<k5>(t), get<k6>(t)); + } +}; + +template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, + int k7> +class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, -1, -1> { + public: + typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), + GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), + GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), + GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), + GMOCK_FIELD_TYPE_(Tuple, k7)> type; + static type GetSelectedFields(const Tuple& t) { + return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), + get<k5>(t), get<k6>(t), get<k7>(t)); + } +}; + +template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, + int k7, int k8> +class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, -1> { + public: + typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), + GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), + GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), + GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), + GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8)> type; + static type GetSelectedFields(const Tuple& t) { + return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), + get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t)); + } +}; + +#undef GMOCK_FIELD_TYPE_ + +// Implements the Args() matcher. +template <class ArgsTuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1, + int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, + int k9 = -1> +class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> { + public: + // ArgsTuple may have top-level const or reference modifiers. + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple; + typedef typename internal::TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5, + k6, k7, k8, k9>::type SelectedArgs; + typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher; + + template <typename InnerMatcher> + explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher) + : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {} + + virtual bool MatchAndExplain(ArgsTuple args, + MatchResultListener* listener) const { + const SelectedArgs& selected_args = GetSelectedArgs(args); + if (!listener->IsInterested()) + return inner_matcher_.Matches(selected_args); + + PrintIndices(listener->stream()); + *listener << "are " << PrintToString(selected_args); + + StringMatchResultListener inner_listener; + const bool match = inner_matcher_.MatchAndExplain(selected_args, + &inner_listener); + PrintIfNotEmpty(inner_listener.str(), listener->stream()); + return match; + } + + virtual void DescribeTo(::std::ostream* os) const { + *os << "are a tuple "; + PrintIndices(os); + inner_matcher_.DescribeTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "are a tuple "; + PrintIndices(os); + inner_matcher_.DescribeNegationTo(os); + } + + private: + static SelectedArgs GetSelectedArgs(ArgsTuple args) { + return TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, + k9>::GetSelectedFields(args); + } + + // Prints the indices of the selected fields. + static void PrintIndices(::std::ostream* os) { + *os << "whose fields ("; + const int indices[10] = { k0, k1, k2, k3, k4, k5, k6, k7, k8, k9 }; + for (int i = 0; i < 10; i++) { + if (indices[i] < 0) + break; + + if (i >= 1) + *os << ", "; + + *os << "#" << indices[i]; + } + *os << ") "; + } + + const MonomorphicInnerMatcher inner_matcher_; + + GTEST_DISALLOW_ASSIGN_(ArgsMatcherImpl); +}; + +template <class InnerMatcher, int k0 = -1, int k1 = -1, int k2 = -1, + int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, + int k8 = -1, int k9 = -1> +class ArgsMatcher { + public: + explicit ArgsMatcher(const InnerMatcher& inner_matcher) + : inner_matcher_(inner_matcher) {} + + template <typename ArgsTuple> + operator Matcher<ArgsTuple>() const { + return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k0, k1, k2, k3, k4, k5, + k6, k7, k8, k9>(inner_matcher_)); + } + + private: + const InnerMatcher inner_matcher_; + + GTEST_DISALLOW_ASSIGN_(ArgsMatcher); +}; + +// A set of metafunctions for computing the result type of AllOf. +// AllOf(m1, ..., mN) returns +// AllOfResultN<decltype(m1), ..., decltype(mN)>::type. + +// Although AllOf isn't defined for one argument, AllOfResult1 is defined +// to simplify the implementation. +template <typename M1> +struct AllOfResult1 { + typedef M1 type; +}; + +template <typename M1, typename M2> +struct AllOfResult2 { + typedef BothOfMatcher< + typename AllOfResult1<M1>::type, + typename AllOfResult1<M2>::type + > type; +}; + +template <typename M1, typename M2, typename M3> +struct AllOfResult3 { + typedef BothOfMatcher< + typename AllOfResult1<M1>::type, + typename AllOfResult2<M2, M3>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4> +struct AllOfResult4 { + typedef BothOfMatcher< + typename AllOfResult2<M1, M2>::type, + typename AllOfResult2<M3, M4>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5> +struct AllOfResult5 { + typedef BothOfMatcher< + typename AllOfResult2<M1, M2>::type, + typename AllOfResult3<M3, M4, M5>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6> +struct AllOfResult6 { + typedef BothOfMatcher< + typename AllOfResult3<M1, M2, M3>::type, + typename AllOfResult3<M4, M5, M6>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7> +struct AllOfResult7 { + typedef BothOfMatcher< + typename AllOfResult3<M1, M2, M3>::type, + typename AllOfResult4<M4, M5, M6, M7>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8> +struct AllOfResult8 { + typedef BothOfMatcher< + typename AllOfResult4<M1, M2, M3, M4>::type, + typename AllOfResult4<M5, M6, M7, M8>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8, typename M9> +struct AllOfResult9 { + typedef BothOfMatcher< + typename AllOfResult4<M1, M2, M3, M4>::type, + typename AllOfResult5<M5, M6, M7, M8, M9>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8, typename M9, typename M10> +struct AllOfResult10 { + typedef BothOfMatcher< + typename AllOfResult5<M1, M2, M3, M4, M5>::type, + typename AllOfResult5<M6, M7, M8, M9, M10>::type + > type; +}; + +// A set of metafunctions for computing the result type of AnyOf. +// AnyOf(m1, ..., mN) returns +// AnyOfResultN<decltype(m1), ..., decltype(mN)>::type. + +// Although AnyOf isn't defined for one argument, AnyOfResult1 is defined +// to simplify the implementation. +template <typename M1> +struct AnyOfResult1 { + typedef M1 type; +}; + +template <typename M1, typename M2> +struct AnyOfResult2 { + typedef EitherOfMatcher< + typename AnyOfResult1<M1>::type, + typename AnyOfResult1<M2>::type + > type; +}; + +template <typename M1, typename M2, typename M3> +struct AnyOfResult3 { + typedef EitherOfMatcher< + typename AnyOfResult1<M1>::type, + typename AnyOfResult2<M2, M3>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4> +struct AnyOfResult4 { + typedef EitherOfMatcher< + typename AnyOfResult2<M1, M2>::type, + typename AnyOfResult2<M3, M4>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5> +struct AnyOfResult5 { + typedef EitherOfMatcher< + typename AnyOfResult2<M1, M2>::type, + typename AnyOfResult3<M3, M4, M5>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6> +struct AnyOfResult6 { + typedef EitherOfMatcher< + typename AnyOfResult3<M1, M2, M3>::type, + typename AnyOfResult3<M4, M5, M6>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7> +struct AnyOfResult7 { + typedef EitherOfMatcher< + typename AnyOfResult3<M1, M2, M3>::type, + typename AnyOfResult4<M4, M5, M6, M7>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8> +struct AnyOfResult8 { + typedef EitherOfMatcher< + typename AnyOfResult4<M1, M2, M3, M4>::type, + typename AnyOfResult4<M5, M6, M7, M8>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8, typename M9> +struct AnyOfResult9 { + typedef EitherOfMatcher< + typename AnyOfResult4<M1, M2, M3, M4>::type, + typename AnyOfResult5<M5, M6, M7, M8, M9>::type + > type; +}; + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8, typename M9, typename M10> +struct AnyOfResult10 { + typedef EitherOfMatcher< + typename AnyOfResult5<M1, M2, M3, M4, M5>::type, + typename AnyOfResult5<M6, M7, M8, M9, M10>::type + > type; +}; + +} // namespace internal + +// Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected +// fields of it matches a_matcher. C++ doesn't support default +// arguments for function templates, so we have to overload it. +template <typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher>(matcher); +} + +template <int k1, typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher, k1> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher, k1>(matcher); +} + +template <int k1, int k2, typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher, k1, k2> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher, k1, k2>(matcher); +} + +template <int k1, int k2, int k3, typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher, k1, k2, k3>(matcher); +} + +template <int k1, int k2, int k3, int k4, typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4>(matcher); +} + +template <int k1, int k2, int k3, int k4, int k5, typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5>(matcher); +} + +template <int k1, int k2, int k3, int k4, int k5, int k6, typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6>(matcher); +} + +template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, + typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, + k7>(matcher); +} + +template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, + typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, + k8>(matcher); +} + +template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, + int k9, typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, + k9>(matcher); +} + +template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, + int k9, int k10, typename InnerMatcher> +inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9, + k10> +Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, + k9, k10>(matcher); +} + +// ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with +// n elements, where the i-th element in the container must +// match the i-th argument in the list. Each argument of +// ElementsAre() can be either a value or a matcher. We support up to +// 10 arguments. +// +// The use of DecayArray in the implementation allows ElementsAre() +// to accept string literals, whose type is const char[N], but we +// want to treat them as const char*. +// +// NOTE: Since ElementsAre() cares about the order of the elements, it +// must not be used with containers whose elements's order is +// undefined (e.g. hash_map). + +inline internal::ElementsAreMatcher< + ::testing::tuple<> > +ElementsAre() { + typedef ::testing::tuple<> Args; + return internal::ElementsAreMatcher<Args>(Args()); +} + +template <typename T1> +inline internal::ElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type> > +ElementsAre(const T1& e1) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type> Args; + return internal::ElementsAreMatcher<Args>(Args(e1)); +} + +template <typename T1, typename T2> +inline internal::ElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type> > +ElementsAre(const T1& e1, const T2& e2) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type> Args; + return internal::ElementsAreMatcher<Args>(Args(e1, e2)); +} + +template <typename T1, typename T2, typename T3> +inline internal::ElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type> Args; + return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3)); +} + +template <typename T1, typename T2, typename T3, typename T4> +inline internal::ElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type> Args; + return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5> +inline internal::ElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type> Args; + return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6> +inline internal::ElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5, const T6& e6) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type> Args; + return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6, typename T7> +inline internal::ElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5, const T6& e6, const T7& e7) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type> Args; + return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6, typename T7, typename T8> +inline internal::ElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5, const T6& e6, const T7& e7, const T8& e8) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type> Args; + return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, + e8)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6, typename T7, typename T8, typename T9> +inline internal::ElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type, + typename internal::DecayArray<T9>::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type, + typename internal::DecayArray<T9>::type> Args; + return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, + e8, e9)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6, typename T7, typename T8, typename T9, typename T10> +inline internal::ElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type, + typename internal::DecayArray<T9>::type, + typename internal::DecayArray<T10>::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9, + const T10& e10) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type, + typename internal::DecayArray<T9>::type, + typename internal::DecayArray<T10>::type> Args; + return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, + e8, e9, e10)); +} + +// UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension +// that matches n elements in any order. We support up to n=10 arguments. + +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple<> > +UnorderedElementsAre() { + typedef ::testing::tuple<> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args()); +} + +template <typename T1> +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type> > +UnorderedElementsAre(const T1& e1) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args(e1)); +} + +template <typename T1, typename T2> +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type> > +UnorderedElementsAre(const T1& e1, const T2& e2) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2)); +} + +template <typename T1, typename T2, typename T3> +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3)); +} + +template <typename T1, typename T2, typename T3, typename T4> +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5> +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6> +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5, const T6& e6) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, + e6)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6, typename T7> +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5, const T6& e6, const T7& e7) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, + e6, e7)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6, typename T7, typename T8> +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5, const T6& e6, const T7& e7, const T8& e8) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, + e6, e7, e8)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6, typename T7, typename T8, typename T9> +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type, + typename internal::DecayArray<T9>::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type, + typename internal::DecayArray<T9>::type> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, + e6, e7, e8, e9)); +} + +template <typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6, typename T7, typename T8, typename T9, typename T10> +inline internal::UnorderedElementsAreMatcher< + ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type, + typename internal::DecayArray<T9>::type, + typename internal::DecayArray<T10>::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, + const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9, + const T10& e10) { + typedef ::testing::tuple< + typename internal::DecayArray<T1>::type, + typename internal::DecayArray<T2>::type, + typename internal::DecayArray<T3>::type, + typename internal::DecayArray<T4>::type, + typename internal::DecayArray<T5>::type, + typename internal::DecayArray<T6>::type, + typename internal::DecayArray<T7>::type, + typename internal::DecayArray<T8>::type, + typename internal::DecayArray<T9>::type, + typename internal::DecayArray<T10>::type> Args; + return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, + e6, e7, e8, e9, e10)); +} + +// AllOf(m1, m2, ..., mk) matches any value that matches all of the given +// sub-matchers. AllOf is called fully qualified to prevent ADL from firing. + +template <typename M1, typename M2> +inline typename internal::AllOfResult2<M1, M2>::type +AllOf(M1 m1, M2 m2) { + return typename internal::AllOfResult2<M1, M2>::type( + m1, + m2); +} + +template <typename M1, typename M2, typename M3> +inline typename internal::AllOfResult3<M1, M2, M3>::type +AllOf(M1 m1, M2 m2, M3 m3) { + return typename internal::AllOfResult3<M1, M2, M3>::type( + m1, + ::testing::AllOf(m2, m3)); +} + +template <typename M1, typename M2, typename M3, typename M4> +inline typename internal::AllOfResult4<M1, M2, M3, M4>::type +AllOf(M1 m1, M2 m2, M3 m3, M4 m4) { + return typename internal::AllOfResult4<M1, M2, M3, M4>::type( + ::testing::AllOf(m1, m2), + ::testing::AllOf(m3, m4)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5> +inline typename internal::AllOfResult5<M1, M2, M3, M4, M5>::type +AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) { + return typename internal::AllOfResult5<M1, M2, M3, M4, M5>::type( + ::testing::AllOf(m1, m2), + ::testing::AllOf(m3, m4, m5)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6> +inline typename internal::AllOfResult6<M1, M2, M3, M4, M5, M6>::type +AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) { + return typename internal::AllOfResult6<M1, M2, M3, M4, M5, M6>::type( + ::testing::AllOf(m1, m2, m3), + ::testing::AllOf(m4, m5, m6)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7> +inline typename internal::AllOfResult7<M1, M2, M3, M4, M5, M6, M7>::type +AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) { + return typename internal::AllOfResult7<M1, M2, M3, M4, M5, M6, M7>::type( + ::testing::AllOf(m1, m2, m3), + ::testing::AllOf(m4, m5, m6, m7)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8> +inline typename internal::AllOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type +AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) { + return typename internal::AllOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type( + ::testing::AllOf(m1, m2, m3, m4), + ::testing::AllOf(m5, m6, m7, m8)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8, typename M9> +inline typename internal::AllOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type +AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) { + return typename internal::AllOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, + M9>::type( + ::testing::AllOf(m1, m2, m3, m4), + ::testing::AllOf(m5, m6, m7, m8, m9)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8, typename M9, typename M10> +inline typename internal::AllOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, + M10>::type +AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { + return typename internal::AllOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, + M10>::type( + ::testing::AllOf(m1, m2, m3, m4, m5), + ::testing::AllOf(m6, m7, m8, m9, m10)); +} + +// AnyOf(m1, m2, ..., mk) matches any value that matches any of the given +// sub-matchers. AnyOf is called fully qualified to prevent ADL from firing. + +template <typename M1, typename M2> +inline typename internal::AnyOfResult2<M1, M2>::type +AnyOf(M1 m1, M2 m2) { + return typename internal::AnyOfResult2<M1, M2>::type( + m1, + m2); +} + +template <typename M1, typename M2, typename M3> +inline typename internal::AnyOfResult3<M1, M2, M3>::type +AnyOf(M1 m1, M2 m2, M3 m3) { + return typename internal::AnyOfResult3<M1, M2, M3>::type( + m1, + ::testing::AnyOf(m2, m3)); +} + +template <typename M1, typename M2, typename M3, typename M4> +inline typename internal::AnyOfResult4<M1, M2, M3, M4>::type +AnyOf(M1 m1, M2 m2, M3 m3, M4 m4) { + return typename internal::AnyOfResult4<M1, M2, M3, M4>::type( + ::testing::AnyOf(m1, m2), + ::testing::AnyOf(m3, m4)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5> +inline typename internal::AnyOfResult5<M1, M2, M3, M4, M5>::type +AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) { + return typename internal::AnyOfResult5<M1, M2, M3, M4, M5>::type( + ::testing::AnyOf(m1, m2), + ::testing::AnyOf(m3, m4, m5)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6> +inline typename internal::AnyOfResult6<M1, M2, M3, M4, M5, M6>::type +AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) { + return typename internal::AnyOfResult6<M1, M2, M3, M4, M5, M6>::type( + ::testing::AnyOf(m1, m2, m3), + ::testing::AnyOf(m4, m5, m6)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7> +inline typename internal::AnyOfResult7<M1, M2, M3, M4, M5, M6, M7>::type +AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) { + return typename internal::AnyOfResult7<M1, M2, M3, M4, M5, M6, M7>::type( + ::testing::AnyOf(m1, m2, m3), + ::testing::AnyOf(m4, m5, m6, m7)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8> +inline typename internal::AnyOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type +AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) { + return typename internal::AnyOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type( + ::testing::AnyOf(m1, m2, m3, m4), + ::testing::AnyOf(m5, m6, m7, m8)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8, typename M9> +inline typename internal::AnyOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type +AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) { + return typename internal::AnyOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, + M9>::type( + ::testing::AnyOf(m1, m2, m3, m4), + ::testing::AnyOf(m5, m6, m7, m8, m9)); +} + +template <typename M1, typename M2, typename M3, typename M4, typename M5, + typename M6, typename M7, typename M8, typename M9, typename M10> +inline typename internal::AnyOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, + M10>::type +AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { + return typename internal::AnyOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, + M10>::type( + ::testing::AnyOf(m1, m2, m3, m4, m5), + ::testing::AnyOf(m6, m7, m8, m9, m10)); +} + +} // namespace testing + + +// The MATCHER* family of macros can be used in a namespace scope to +// define custom matchers easily. +// +// Basic Usage +// =========== +// +// The syntax +// +// MATCHER(name, description_string) { statements; } +// +// defines a matcher with the given name that executes the statements, +// which must return a bool to indicate if the match succeeds. Inside +// the statements, you can refer to the value being matched by 'arg', +// and refer to its type by 'arg_type'. +// +// The description string documents what the matcher does, and is used +// to generate the failure message when the match fails. Since a +// MATCHER() is usually defined in a header file shared by multiple +// C++ source files, we require the description to be a C-string +// literal to avoid possible side effects. It can be empty, in which +// case we'll use the sequence of words in the matcher name as the +// description. +// +// For example: +// +// MATCHER(IsEven, "") { return (arg % 2) == 0; } +// +// allows you to write +// +// // Expects mock_foo.Bar(n) to be called where n is even. +// EXPECT_CALL(mock_foo, Bar(IsEven())); +// +// or, +// +// // Verifies that the value of some_expression is even. +// EXPECT_THAT(some_expression, IsEven()); +// +// If the above assertion fails, it will print something like: +// +// Value of: some_expression +// Expected: is even +// Actual: 7 +// +// where the description "is even" is automatically calculated from the +// matcher name IsEven. +// +// Argument Type +// ============= +// +// Note that the type of the value being matched (arg_type) is +// determined by the context in which you use the matcher and is +// supplied to you by the compiler, so you don't need to worry about +// declaring it (nor can you). This allows the matcher to be +// polymorphic. For example, IsEven() can be used to match any type +// where the value of "(arg % 2) == 0" can be implicitly converted to +// a bool. In the "Bar(IsEven())" example above, if method Bar() +// takes an int, 'arg_type' will be int; if it takes an unsigned long, +// 'arg_type' will be unsigned long; and so on. +// +// Parameterizing Matchers +// ======================= +// +// Sometimes you'll want to parameterize the matcher. For that you +// can use another macro: +// +// MATCHER_P(name, param_name, description_string) { statements; } +// +// For example: +// +// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } +// +// will allow you to write: +// +// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); +// +// which may lead to this message (assuming n is 10): +// +// Value of: Blah("a") +// Expected: has absolute value 10 +// Actual: -9 +// +// Note that both the matcher description and its parameter are +// printed, making the message human-friendly. +// +// In the matcher definition body, you can write 'foo_type' to +// reference the type of a parameter named 'foo'. For example, in the +// body of MATCHER_P(HasAbsoluteValue, value) above, you can write +// 'value_type' to refer to the type of 'value'. +// +// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P10 to +// support multi-parameter matchers. +// +// Describing Parameterized Matchers +// ================================= +// +// The last argument to MATCHER*() is a string-typed expression. The +// expression can reference all of the matcher's parameters and a +// special bool-typed variable named 'negation'. When 'negation' is +// false, the expression should evaluate to the matcher's description; +// otherwise it should evaluate to the description of the negation of +// the matcher. For example, +// +// using testing::PrintToString; +// +// MATCHER_P2(InClosedRange, low, hi, +// string(negation ? "is not" : "is") + " in range [" + +// PrintToString(low) + ", " + PrintToString(hi) + "]") { +// return low <= arg && arg <= hi; +// } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: is in range [4, 6] +// ... +// Expected: is not in range [2, 4] +// +// If you specify "" as the description, the failure message will +// contain the sequence of words in the matcher name followed by the +// parameter values printed as a tuple. For example, +// +// MATCHER_P2(InClosedRange, low, hi, "") { ... } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: in closed range (4, 6) +// ... +// Expected: not (in closed range (2, 4)) +// +// Types of Matcher Parameters +// =========================== +// +// For the purpose of typing, you can view +// +// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } +// +// as shorthand for +// +// template <typename p1_type, ..., typename pk_type> +// FooMatcherPk<p1_type, ..., pk_type> +// Foo(p1_type p1, ..., pk_type pk) { ... } +// +// When you write Foo(v1, ..., vk), the compiler infers the types of +// the parameters v1, ..., and vk for you. If you are not happy with +// the result of the type inference, you can specify the types by +// explicitly instantiating the template, as in Foo<long, bool>(5, +// false). As said earlier, you don't get to (or need to) specify +// 'arg_type' as that's determined by the context in which the matcher +// is used. You can assign the result of expression Foo(p1, ..., pk) +// to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This +// can be useful when composing matchers. +// +// While you can instantiate a matcher template with reference types, +// passing the parameters by pointer usually makes your code more +// readable. If, however, you still want to pass a parameter by +// reference, be aware that in the failure message generated by the +// matcher you will see the value of the referenced object but not its +// address. +// +// Explaining Match Results +// ======================== +// +// Sometimes the matcher description alone isn't enough to explain why +// the match has failed or succeeded. For example, when expecting a +// long string, it can be very helpful to also print the diff between +// the expected string and the actual one. To achieve that, you can +// optionally stream additional information to a special variable +// named result_listener, whose type is a pointer to class +// MatchResultListener: +// +// MATCHER_P(EqualsLongString, str, "") { +// if (arg == str) return true; +// +// *result_listener << "the difference: " +/// << DiffStrings(str, arg); +// return false; +// } +// +// Overloading Matchers +// ==================== +// +// You can overload matchers with different numbers of parameters: +// +// MATCHER_P(Blah, a, description_string1) { ... } +// MATCHER_P2(Blah, a, b, description_string2) { ... } +// +// Caveats +// ======= +// +// When defining a new matcher, you should also consider implementing +// MatcherInterface or using MakePolymorphicMatcher(). These +// approaches require more work than the MATCHER* macros, but also +// give you more control on the types of the value being matched and +// the matcher parameters, which may leads to better compiler error +// messages when the matcher is used wrong. They also allow +// overloading matchers based on parameter types (as opposed to just +// based on the number of parameters). +// +// MATCHER*() can only be used in a namespace scope. The reason is +// that C++ doesn't yet allow function-local types to be used to +// instantiate templates. The up-coming C++0x standard will fix this. +// Once that's done, we'll consider supporting using MATCHER*() inside +// a function. +// +// More Information +// ================ +// +// To learn more about using these macros, please search for 'MATCHER' +// on http://code.google.com/p/googlemock/wiki/CookBook. + +#define MATCHER(name, description)\ + class name##Matcher {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + gmock_Impl()\ + {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<>()));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>());\ + }\ + name##Matcher() {\ + }\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##Matcher);\ + };\ + inline name##Matcher name() {\ + return name##Matcher();\ + }\ + template <typename arg_type>\ + bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#define MATCHER_P(name, p0, description)\ + template <typename p0##_type>\ + class name##MatcherP {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + explicit gmock_Impl(p0##_type gmock_p0)\ + : p0(gmock_p0) {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + p0##_type p0;\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<p0##_type>(p0)));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>(p0));\ + }\ + explicit name##MatcherP(p0##_type gmock_p0) : p0(gmock_p0) {\ + }\ + p0##_type p0;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##MatcherP);\ + };\ + template <typename p0##_type>\ + inline name##MatcherP<p0##_type> name(p0##_type p0) {\ + return name##MatcherP<p0##_type>(p0);\ + }\ + template <typename p0##_type>\ + template <typename arg_type>\ + bool name##MatcherP<p0##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#define MATCHER_P2(name, p0, p1, description)\ + template <typename p0##_type, typename p1##_type>\ + class name##MatcherP2 {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\ + : p0(gmock_p0), p1(gmock_p1) {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + p0##_type p0;\ + p1##_type p1;\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<p0##_type, p1##_type>(p0, p1)));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>(p0, p1));\ + }\ + name##MatcherP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ + p1(gmock_p1) {\ + }\ + p0##_type p0;\ + p1##_type p1;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##MatcherP2);\ + };\ + template <typename p0##_type, typename p1##_type>\ + inline name##MatcherP2<p0##_type, p1##_type> name(p0##_type p0, \ + p1##_type p1) {\ + return name##MatcherP2<p0##_type, p1##_type>(p0, p1);\ + }\ + template <typename p0##_type, typename p1##_type>\ + template <typename arg_type>\ + bool name##MatcherP2<p0##_type, \ + p1##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#define MATCHER_P3(name, p0, p1, p2, description)\ + template <typename p0##_type, typename p1##_type, typename p2##_type>\ + class name##MatcherP3 {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<p0##_type, p1##_type, p2##_type>(p0, p1, \ + p2)));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>(p0, p1, p2));\ + }\ + name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##MatcherP3);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type>\ + inline name##MatcherP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \ + p1##_type p1, p2##_type p2) {\ + return name##MatcherP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type>\ + template <typename arg_type>\ + bool name##MatcherP3<p0##_type, p1##_type, \ + p2##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#define MATCHER_P4(name, p0, p1, p2, p3, description)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type>\ + class name##MatcherP4 {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3)\ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<p0##_type, p1##_type, p2##_type, \ + p3##_type>(p0, p1, p2, p3)));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>(p0, p1, p2, p3));\ + }\ + name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \ + p2(gmock_p2), p3(gmock_p3) {\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##MatcherP4);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type>\ + inline name##MatcherP4<p0##_type, p1##_type, p2##_type, \ + p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \ + p3##_type p3) {\ + return name##MatcherP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, \ + p1, p2, p3);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type>\ + template <typename arg_type>\ + bool name##MatcherP4<p0##_type, p1##_type, p2##_type, \ + p3##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#define MATCHER_P5(name, p0, p1, p2, p3, p4, description)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type>\ + class name##MatcherP5 {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4)\ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ + p4(gmock_p4) {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type>(p0, p1, p2, p3, p4)));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>(p0, p1, p2, p3, p4));\ + }\ + name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, \ + p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4) {\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##MatcherP5);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type>\ + inline name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ + p4##_type p4) {\ + return name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type>(p0, p1, p2, p3, p4);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type>\ + template <typename arg_type>\ + bool name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type>\ + class name##MatcherP6 {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)\ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ + p4(gmock_p4), p5(gmock_p5) {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5)));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5));\ + }\ + name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##MatcherP6);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type>\ + inline name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \ + p3##_type p3, p4##_type p4, p5##_type p5) {\ + return name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type>\ + template <typename arg_type>\ + bool name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type>\ + class name##MatcherP7 {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6)\ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ + p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, \ + p6)));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6));\ + }\ + name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \ + p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \ + p6(gmock_p6) {\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##MatcherP7);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type>\ + inline name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \ + p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ + p6##_type p6) {\ + return name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type>\ + template <typename arg_type>\ + bool name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type, p6##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type>\ + class name##MatcherP8 {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7)\ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ + p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, \ + p3, p4, p5, p6, p7)));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7));\ + }\ + name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, \ + p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ + p7(gmock_p7) {\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##MatcherP8);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type>\ + inline name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \ + p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ + p6##_type p6, p7##_type p7) {\ + return name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \ + p6, p7);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type>\ + template <typename arg_type>\ + bool name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type, p6##_type, \ + p7##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type>\ + class name##MatcherP9 {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)\ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ + p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ + p8(gmock_p8) {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + p8##_type p8;\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, \ + p8##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8));\ + }\ + name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ + p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ + p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ + p8(gmock_p8) {\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + p8##_type p8;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##MatcherP9);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type>\ + inline name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, \ + p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ + p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ + p8##_type p8) {\ + return name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \ + p3, p4, p5, p6, p7, p8);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type>\ + template <typename arg_type>\ + bool name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ + p5##_type, p6##_type, p7##_type, \ + p8##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type, \ + typename p9##_type>\ + class name##MatcherP10 {\ + public:\ + template <typename arg_type>\ + class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + public:\ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ + p9##_type gmock_p9)\ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ + p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ + p8(gmock_p8), p9(gmock_p9) {}\ + virtual bool MatchAndExplain(\ + arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + virtual void DescribeTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(false);\ + }\ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + *gmock_os << FormatDescription(true);\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + p8##_type p8;\ + p9##_type p9;\ + private:\ + ::testing::internal::string FormatDescription(bool negation) const {\ + const ::testing::internal::string gmock_description = (description);\ + if (!gmock_description.empty())\ + return gmock_description;\ + return ::testing::internal::FormatMatcherDescription(\ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ + ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ + p9##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\ + }\ + GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ + };\ + template <typename arg_type>\ + operator ::testing::Matcher<arg_type>() const {\ + return ::testing::Matcher<arg_type>(\ + new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9));\ + }\ + name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, \ + p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ + p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \ + p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ + p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {\ + }\ + p0##_type p0;\ + p1##_type p1;\ + p2##_type p2;\ + p3##_type p3;\ + p4##_type p4;\ + p5##_type p5;\ + p6##_type p6;\ + p7##_type p7;\ + p8##_type p8;\ + p9##_type p9;\ + private:\ + GTEST_DISALLOW_ASSIGN_(name##MatcherP10);\ + };\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type, \ + typename p9##_type>\ + inline name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ + p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ + p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ + p9##_type p9) {\ + return name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \ + p1, p2, p3, p4, p5, p6, p7, p8, p9);\ + }\ + template <typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type, \ + typename p9##_type>\ + template <typename arg_type>\ + bool name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \ + p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ + p9##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ + arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ + const + +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-nice-strict.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-nice-strict.h new file mode 100644 index 00000000000..4095f4d5bc7 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-generated-nice-strict.h @@ -0,0 +1,397 @@ +// This file was GENERATED by command: +// pump.py gmock-generated-nice-strict.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Implements class templates NiceMock, NaggyMock, and StrictMock. +// +// Given a mock class MockFoo that is created using Google Mock, +// NiceMock<MockFoo> is a subclass of MockFoo that allows +// uninteresting calls (i.e. calls to mock methods that have no +// EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo +// that prints a warning when an uninteresting call occurs, and +// StrictMock<MockFoo> is a subclass of MockFoo that treats all +// uninteresting calls as errors. +// +// Currently a mock is naggy by default, so MockFoo and +// NaggyMock<MockFoo> behave like the same. However, we will soon +// switch the default behavior of mocks to be nice, as that in general +// leads to more maintainable tests. When that happens, MockFoo will +// stop behaving like NaggyMock<MockFoo> and start behaving like +// NiceMock<MockFoo>. +// +// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of +// their respective base class, with up-to 10 arguments. Therefore +// you can write NiceMock<MockFoo>(5, "a") to construct a nice mock +// where MockFoo has a constructor that accepts (int, const char*), +// for example. +// +// A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>, +// and StrictMock<MockFoo> only works for mock methods defined using +// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class. +// If a mock method is defined in a base class of MockFoo, the "nice" +// or "strict" modifier may not affect it, depending on the compiler. +// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT +// supported. +// +// Another known limitation is that the constructors of the base mock +// cannot have arguments passed by non-const reference, which are +// banned by the Google C++ style guide anyway. + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ + +#include "gmock/gmock-spec-builders.h" +#include "gmock/internal/gmock-port.h" + +namespace testing { + +template <class MockClass> +class NiceMock : public MockClass { + public: + // We don't factor out the constructor body to a common method, as + // we have to avoid a possible clash with members of MockClass. + NiceMock() { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + // C++ doesn't (yet) allow inheritance of constructors, so we have + // to define it for each arity. + template <typename A1> + explicit NiceMock(const A1& a1) : MockClass(a1) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + template <typename A1, typename A2> + NiceMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3> + NiceMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4> + NiceMock(const A1& a1, const A2& a2, const A3& a3, + const A4& a4) : MockClass(a1, a2, a3, a4) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5> + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5) : MockClass(a1, a2, a3, a4, a5) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6> + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7> + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, + a6, a7) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8> + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, + a2, a3, a4, a5, a6, a7, a8) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8, typename A9> + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7, const A8& a8, + const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8, typename A9, typename A10> + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, + const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + virtual ~NiceMock() { + ::testing::Mock::UnregisterCallReaction( + internal::ImplicitCast_<MockClass*>(this)); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock); +}; + +template <class MockClass> +class NaggyMock : public MockClass { + public: + // We don't factor out the constructor body to a common method, as + // we have to avoid a possible clash with members of MockClass. + NaggyMock() { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + // C++ doesn't (yet) allow inheritance of constructors, so we have + // to define it for each arity. + template <typename A1> + explicit NaggyMock(const A1& a1) : MockClass(a1) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + template <typename A1, typename A2> + NaggyMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3> + NaggyMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4> + NaggyMock(const A1& a1, const A2& a2, const A3& a3, + const A4& a4) : MockClass(a1, a2, a3, a4) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5> + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5) : MockClass(a1, a2, a3, a4, a5) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6> + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7> + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, + a6, a7) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8> + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, + a2, a3, a4, a5, a6, a7, a8) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8, typename A9> + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7, const A8& a8, + const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8, typename A9, typename A10> + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, + const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + virtual ~NaggyMock() { + ::testing::Mock::UnregisterCallReaction( + internal::ImplicitCast_<MockClass*>(this)); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock); +}; + +template <class MockClass> +class StrictMock : public MockClass { + public: + // We don't factor out the constructor body to a common method, as + // we have to avoid a possible clash with members of MockClass. + StrictMock() { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + // C++ doesn't (yet) allow inheritance of constructors, so we have + // to define it for each arity. + template <typename A1> + explicit StrictMock(const A1& a1) : MockClass(a1) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + template <typename A1, typename A2> + StrictMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3> + StrictMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4> + StrictMock(const A1& a1, const A2& a2, const A3& a3, + const A4& a4) : MockClass(a1, a2, a3, a4) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5> + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5) : MockClass(a1, a2, a3, a4, a5) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6> + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7> + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, + a6, a7) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8> + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, + a2, a3, a4, a5, a6, a7, a8) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8, typename A9> + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7, const A8& a8, + const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8, typename A9, typename A10> + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, + const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, + const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + virtual ~StrictMock() { + ::testing::Mock::UnregisterCallReaction( + internal::ImplicitCast_<MockClass*>(this)); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock); +}; + +// The following specializations catch some (relatively more common) +// user errors of nesting nice and strict mocks. They do NOT catch +// all possible errors. + +// These specializations are declared but not defined, as NiceMock, +// NaggyMock, and StrictMock cannot be nested. + +template <typename MockClass> +class NiceMock<NiceMock<MockClass> >; +template <typename MockClass> +class NiceMock<NaggyMock<MockClass> >; +template <typename MockClass> +class NiceMock<StrictMock<MockClass> >; + +template <typename MockClass> +class NaggyMock<NiceMock<MockClass> >; +template <typename MockClass> +class NaggyMock<NaggyMock<MockClass> >; +template <typename MockClass> +class NaggyMock<StrictMock<MockClass> >; + +template <typename MockClass> +class StrictMock<NiceMock<MockClass> >; +template <typename MockClass> +class StrictMock<NaggyMock<MockClass> >; +template <typename MockClass> +class StrictMock<StrictMock<MockClass> >; + +} // namespace testing + +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-matchers.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-matchers.h new file mode 100644 index 00000000000..749a30e4e6d --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-matchers.h @@ -0,0 +1,4415 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some commonly used argument matchers. More +// matchers can be defined by the user implementing the +// MatcherInterface<T> interface if necessary. + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ + +#include <math.h> +#include <algorithm> +#include <iterator> +#include <limits> +#include <ostream> // NOLINT +#include <sstream> +#include <string> +#include <utility> +#include <vector> + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +# include <initializer_list> // NOLINT -- must be after gtest.h +#endif + +namespace testing { + +// To implement a matcher Foo for type T, define: +// 1. a class FooMatcherImpl that implements the +// MatcherInterface<T> interface, and +// 2. a factory function that creates a Matcher<T> object from a +// FooMatcherImpl*. +// +// The two-level delegation design makes it possible to allow a user +// to write "v" instead of "Eq(v)" where a Matcher is expected, which +// is impossible if we pass matchers by pointers. It also eases +// ownership management as Matcher objects can now be copied like +// plain values. + +// MatchResultListener is an abstract class. Its << operator can be +// used by a matcher to explain why a value matches or doesn't match. +// +// TODO(wan@google.com): add method +// bool InterestedInWhy(bool result) const; +// to indicate whether the listener is interested in why the match +// result is 'result'. +class MatchResultListener { + public: + // Creates a listener object with the given underlying ostream. The + // listener does not own the ostream, and does not dereference it + // in the constructor or destructor. + explicit MatchResultListener(::std::ostream* os) : stream_(os) {} + virtual ~MatchResultListener() = 0; // Makes this class abstract. + + // Streams x to the underlying ostream; does nothing if the ostream + // is NULL. + template <typename T> + MatchResultListener& operator<<(const T& x) { + if (stream_ != NULL) + *stream_ << x; + return *this; + } + + // Returns the underlying ostream. + ::std::ostream* stream() { return stream_; } + + // Returns true iff the listener is interested in an explanation of + // the match result. A matcher's MatchAndExplain() method can use + // this information to avoid generating the explanation when no one + // intends to hear it. + bool IsInterested() const { return stream_ != NULL; } + + private: + ::std::ostream* const stream_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener); +}; + +inline MatchResultListener::~MatchResultListener() { +} + +// An instance of a subclass of this knows how to describe itself as a +// matcher. +class MatcherDescriberInterface { + public: + virtual ~MatcherDescriberInterface() {} + + // Describes this matcher to an ostream. The function should print + // a verb phrase that describes the property a value matching this + // matcher should have. The subject of the verb phrase is the value + // being matched. For example, the DescribeTo() method of the Gt(7) + // matcher prints "is greater than 7". + virtual void DescribeTo(::std::ostream* os) const = 0; + + // Describes the negation of this matcher to an ostream. For + // example, if the description of this matcher is "is greater than + // 7", the negated description could be "is not greater than 7". + // You are not required to override this when implementing + // MatcherInterface, but it is highly advised so that your matcher + // can produce good error messages. + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "not ("; + DescribeTo(os); + *os << ")"; + } +}; + +// The implementation of a matcher. +template <typename T> +class MatcherInterface : public MatcherDescriberInterface { + public: + // Returns true iff the matcher matches x; also explains the match + // result to 'listener' if necessary (see the next paragraph), in + // the form of a non-restrictive relative clause ("which ...", + // "whose ...", etc) that describes x. For example, the + // MatchAndExplain() method of the Pointee(...) matcher should + // generate an explanation like "which points to ...". + // + // Implementations of MatchAndExplain() should add an explanation of + // the match result *if and only if* they can provide additional + // information that's not already present (or not obvious) in the + // print-out of x and the matcher's description. Whether the match + // succeeds is not a factor in deciding whether an explanation is + // needed, as sometimes the caller needs to print a failure message + // when the match succeeds (e.g. when the matcher is used inside + // Not()). + // + // For example, a "has at least 10 elements" matcher should explain + // what the actual element count is, regardless of the match result, + // as it is useful information to the reader; on the other hand, an + // "is empty" matcher probably only needs to explain what the actual + // size is when the match fails, as it's redundant to say that the + // size is 0 when the value is already known to be empty. + // + // You should override this method when defining a new matcher. + // + // It's the responsibility of the caller (Google Mock) to guarantee + // that 'listener' is not NULL. This helps to simplify a matcher's + // implementation when it doesn't care about the performance, as it + // can talk to 'listener' without checking its validity first. + // However, in order to implement dummy listeners efficiently, + // listener->stream() may be NULL. + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; + + // Inherits these methods from MatcherDescriberInterface: + // virtual void DescribeTo(::std::ostream* os) const = 0; + // virtual void DescribeNegationTo(::std::ostream* os) const; +}; + +// A match result listener that stores the explanation in a string. +class StringMatchResultListener : public MatchResultListener { + public: + StringMatchResultListener() : MatchResultListener(&ss_) {} + + // Returns the explanation accumulated so far. + internal::string str() const { return ss_.str(); } + + // Clears the explanation accumulated so far. + void Clear() { ss_.str(""); } + + private: + ::std::stringstream ss_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener); +}; + +namespace internal { + +struct AnyEq { + template <typename A, typename B> + bool operator()(const A& a, const B& b) const { return a == b; } +}; +struct AnyNe { + template <typename A, typename B> + bool operator()(const A& a, const B& b) const { return a != b; } +}; +struct AnyLt { + template <typename A, typename B> + bool operator()(const A& a, const B& b) const { return a < b; } +}; +struct AnyGt { + template <typename A, typename B> + bool operator()(const A& a, const B& b) const { return a > b; } +}; +struct AnyLe { + template <typename A, typename B> + bool operator()(const A& a, const B& b) const { return a <= b; } +}; +struct AnyGe { + template <typename A, typename B> + bool operator()(const A& a, const B& b) const { return a >= b; } +}; + +// A match result listener that ignores the explanation. +class DummyMatchResultListener : public MatchResultListener { + public: + DummyMatchResultListener() : MatchResultListener(NULL) {} + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener); +}; + +// A match result listener that forwards the explanation to a given +// ostream. The difference between this and MatchResultListener is +// that the former is concrete. +class StreamMatchResultListener : public MatchResultListener { + public: + explicit StreamMatchResultListener(::std::ostream* os) + : MatchResultListener(os) {} + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener); +}; + +// An internal class for implementing Matcher<T>, which will derive +// from it. We put functionalities common to all Matcher<T> +// specializations here to avoid code duplication. +template <typename T> +class MatcherBase { + public: + // Returns true iff the matcher matches x; also explains the match + // result to 'listener'. + bool MatchAndExplain(T x, MatchResultListener* listener) const { + return impl_->MatchAndExplain(x, listener); + } + + // Returns true iff this matcher matches x. + bool Matches(T x) const { + DummyMatchResultListener dummy; + return MatchAndExplain(x, &dummy); + } + + // Describes this matcher to an ostream. + void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } + + // Describes the negation of this matcher to an ostream. + void DescribeNegationTo(::std::ostream* os) const { + impl_->DescribeNegationTo(os); + } + + // Explains why x matches, or doesn't match, the matcher. + void ExplainMatchResultTo(T x, ::std::ostream* os) const { + StreamMatchResultListener listener(os); + MatchAndExplain(x, &listener); + } + + // Returns the describer for this matcher object; retains ownership + // of the describer, which is only guaranteed to be alive when + // this matcher object is alive. + const MatcherDescriberInterface* GetDescriber() const { + return impl_.get(); + } + + protected: + MatcherBase() {} + + // Constructs a matcher from its implementation. + explicit MatcherBase(const MatcherInterface<T>* impl) + : impl_(impl) {} + + virtual ~MatcherBase() {} + + private: + // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar + // interfaces. The former dynamically allocates a chunk of memory + // to hold the reference count, while the latter tracks all + // references using a circular linked list without allocating + // memory. It has been observed that linked_ptr performs better in + // typical scenarios. However, shared_ptr can out-perform + // linked_ptr when there are many more uses of the copy constructor + // than the default constructor. + // + // If performance becomes a problem, we should see if using + // shared_ptr helps. + ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_; +}; + +} // namespace internal + +// A Matcher<T> is a copyable and IMMUTABLE (except by assignment) +// object that can check whether a value of type T matches. The +// implementation of Matcher<T> is just a linked_ptr to const +// MatcherInterface<T>, so copying is fairly cheap. Don't inherit +// from Matcher! +template <typename T> +class Matcher : public internal::MatcherBase<T> { + public: + // Constructs a null matcher. Needed for storing Matcher objects in STL + // containers. A default-constructed matcher is not yet initialized. You + // cannot use it until a valid value has been assigned to it. + explicit Matcher() {} // NOLINT + + // Constructs a matcher from its implementation. + explicit Matcher(const MatcherInterface<T>* impl) + : internal::MatcherBase<T>(impl) {} + + // Implicit constructor here allows people to write + // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes + Matcher(T value); // NOLINT +}; + +// The following two specializations allow the user to write str +// instead of Eq(str) and "foo" instead of Eq("foo") when a string +// matcher is expected. +template <> +class GTEST_API_ Matcher<const internal::string&> + : public internal::MatcherBase<const internal::string&> { + public: + Matcher() {} + + explicit Matcher(const MatcherInterface<const internal::string&>* impl) + : internal::MatcherBase<const internal::string&>(impl) {} + + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a string object. + Matcher(const internal::string& s); // NOLINT + + // Allows the user to write "foo" instead of Eq("foo") sometimes. + Matcher(const char* s); // NOLINT +}; + +template <> +class GTEST_API_ Matcher<internal::string> + : public internal::MatcherBase<internal::string> { + public: + Matcher() {} + + explicit Matcher(const MatcherInterface<internal::string>* impl) + : internal::MatcherBase<internal::string>(impl) {} + + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a string object. + Matcher(const internal::string& s); // NOLINT + + // Allows the user to write "foo" instead of Eq("foo") sometimes. + Matcher(const char* s); // NOLINT +}; + +#if GTEST_HAS_STRING_PIECE_ +// The following two specializations allow the user to write str +// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece +// matcher is expected. +template <> +class GTEST_API_ Matcher<const StringPiece&> + : public internal::MatcherBase<const StringPiece&> { + public: + Matcher() {} + + explicit Matcher(const MatcherInterface<const StringPiece&>* impl) + : internal::MatcherBase<const StringPiece&>(impl) {} + + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a string object. + Matcher(const internal::string& s); // NOLINT + + // Allows the user to write "foo" instead of Eq("foo") sometimes. + Matcher(const char* s); // NOLINT + + // Allows the user to pass StringPieces directly. + Matcher(StringPiece s); // NOLINT +}; + +template <> +class GTEST_API_ Matcher<StringPiece> + : public internal::MatcherBase<StringPiece> { + public: + Matcher() {} + + explicit Matcher(const MatcherInterface<StringPiece>* impl) + : internal::MatcherBase<StringPiece>(impl) {} + + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a string object. + Matcher(const internal::string& s); // NOLINT + + // Allows the user to write "foo" instead of Eq("foo") sometimes. + Matcher(const char* s); // NOLINT + + // Allows the user to pass StringPieces directly. + Matcher(StringPiece s); // NOLINT +}; +#endif // GTEST_HAS_STRING_PIECE_ + +// The PolymorphicMatcher class template makes it easy to implement a +// polymorphic matcher (i.e. a matcher that can match values of more +// than one type, e.g. Eq(n) and NotNull()). +// +// To define a polymorphic matcher, a user should provide an Impl +// class that has a DescribeTo() method and a DescribeNegationTo() +// method, and define a member function (or member function template) +// +// bool MatchAndExplain(const Value& value, +// MatchResultListener* listener) const; +// +// See the definition of NotNull() for a complete example. +template <class Impl> +class PolymorphicMatcher { + public: + explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {} + + // Returns a mutable reference to the underlying matcher + // implementation object. + Impl& mutable_impl() { return impl_; } + + // Returns an immutable reference to the underlying matcher + // implementation object. + const Impl& impl() const { return impl_; } + + template <typename T> + operator Matcher<T>() const { + return Matcher<T>(new MonomorphicImpl<T>(impl_)); + } + + private: + template <typename T> + class MonomorphicImpl : public MatcherInterface<T> { + public: + explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} + + virtual void DescribeTo(::std::ostream* os) const { + impl_.DescribeTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + impl_.DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + return impl_.MatchAndExplain(x, listener); + } + + private: + const Impl impl_; + + GTEST_DISALLOW_ASSIGN_(MonomorphicImpl); + }; + + Impl impl_; + + GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher); +}; + +// Creates a matcher from its implementation. This is easier to use +// than the Matcher<T> constructor as it doesn't require you to +// explicitly write the template argument, e.g. +// +// MakeMatcher(foo); +// vs +// Matcher<const string&>(foo); +template <typename T> +inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) { + return Matcher<T>(impl); +} + +// Creates a polymorphic matcher from its implementation. This is +// easier to use than the PolymorphicMatcher<Impl> constructor as it +// doesn't require you to explicitly write the template argument, e.g. +// +// MakePolymorphicMatcher(foo); +// vs +// PolymorphicMatcher<TypeOfFoo>(foo); +template <class Impl> +inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) { + return PolymorphicMatcher<Impl>(impl); +} + +// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION +// and MUST NOT BE USED IN USER CODE!!! +namespace internal { + +// The MatcherCastImpl class template is a helper for implementing +// MatcherCast(). We need this helper in order to partially +// specialize the implementation of MatcherCast() (C++ allows +// class/struct templates to be partially specialized, but not +// function templates.). + +// This general version is used when MatcherCast()'s argument is a +// polymorphic matcher (i.e. something that can be converted to a +// Matcher but is not one yet; for example, Eq(value)) or a value (for +// example, "hello"). +template <typename T, typename M> +class MatcherCastImpl { + public: + static Matcher<T> Cast(const M& polymorphic_matcher_or_value) { + // M can be a polymorhic matcher, in which case we want to use + // its conversion operator to create Matcher<T>. Or it can be a value + // that should be passed to the Matcher<T>'s constructor. + // + // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a + // polymorphic matcher because it'll be ambiguous if T has an implicit + // constructor from M (this usually happens when T has an implicit + // constructor from any type). + // + // It won't work to unconditionally implict_cast + // polymorphic_matcher_or_value to Matcher<T> because it won't trigger + // a user-defined conversion from M to T if one exists (assuming M is + // a value). + return CastImpl( + polymorphic_matcher_or_value, + BooleanConstant< + internal::ImplicitlyConvertible<M, Matcher<T> >::value>()); + } + + private: + static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) { + // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic + // matcher. It must be a value then. Use direct initialization to create + // a matcher. + return Matcher<T>(ImplicitCast_<T>(value)); + } + + static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value, + BooleanConstant<true>) { + // M is implicitly convertible to Matcher<T>, which means that either + // M is a polymorhpic matcher or Matcher<T> has an implicit constructor + // from M. In both cases using the implicit conversion will produce a + // matcher. + // + // Even if T has an implicit constructor from M, it won't be called because + // creating Matcher<T> would require a chain of two user-defined conversions + // (first to create T from M and then to create Matcher<T> from T). + return polymorphic_matcher_or_value; + } +}; + +// This more specialized version is used when MatcherCast()'s argument +// is already a Matcher. This only compiles when type T can be +// statically converted to type U. +template <typename T, typename U> +class MatcherCastImpl<T, Matcher<U> > { + public: + static Matcher<T> Cast(const Matcher<U>& source_matcher) { + return Matcher<T>(new Impl(source_matcher)); + } + + private: + class Impl : public MatcherInterface<T> { + public: + explicit Impl(const Matcher<U>& source_matcher) + : source_matcher_(source_matcher) {} + + // We delegate the matching logic to the source matcher. + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + return source_matcher_.MatchAndExplain(static_cast<U>(x), listener); + } + + virtual void DescribeTo(::std::ostream* os) const { + source_matcher_.DescribeTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + source_matcher_.DescribeNegationTo(os); + } + + private: + const Matcher<U> source_matcher_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; +}; + +// This even more specialized version is used for efficiently casting +// a matcher to its own type. +template <typename T> +class MatcherCastImpl<T, Matcher<T> > { + public: + static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; } +}; + +} // namespace internal + +// In order to be safe and clear, casting between different matcher +// types is done explicitly via MatcherCast<T>(m), which takes a +// matcher m and returns a Matcher<T>. It compiles only when T can be +// statically converted to the argument type of m. +template <typename T, typename M> +inline Matcher<T> MatcherCast(const M& matcher) { + return internal::MatcherCastImpl<T, M>::Cast(matcher); +} + +// Implements SafeMatcherCast(). +// +// We use an intermediate class to do the actual safe casting as Nokia's +// Symbian compiler cannot decide between +// template <T, M> ... (M) and +// template <T, U> ... (const Matcher<U>&) +// for function templates but can for member function templates. +template <typename T> +class SafeMatcherCastImpl { + public: + // This overload handles polymorphic matchers and values only since + // monomorphic matchers are handled by the next one. + template <typename M> + static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) { + return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value); + } + + // This overload handles monomorphic matchers. + // + // In general, if type T can be implicitly converted to type U, we can + // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is + // contravariant): just keep a copy of the original Matcher<U>, convert the + // argument from type T to U, and then pass it to the underlying Matcher<U>. + // The only exception is when U is a reference and T is not, as the + // underlying Matcher<U> may be interested in the argument's address, which + // is not preserved in the conversion from T to U. + template <typename U> + static inline Matcher<T> Cast(const Matcher<U>& matcher) { + // Enforce that T can be implicitly converted to U. + GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value), + T_must_be_implicitly_convertible_to_U); + // Enforce that we are not converting a non-reference type T to a reference + // type U. + GTEST_COMPILE_ASSERT_( + internal::is_reference<T>::value || !internal::is_reference<U>::value, + cannot_convert_non_referentce_arg_to_reference); + // In case both T and U are arithmetic types, enforce that the + // conversion is not lossy. + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; + const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; + const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; + GTEST_COMPILE_ASSERT_( + kTIsOther || kUIsOther || + (internal::LosslessArithmeticConvertible<RawT, RawU>::value), + conversion_of_arithmetic_types_must_be_lossless); + return MatcherCast<T>(matcher); + } +}; + +template <typename T, typename M> +inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) { + return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher); +} + +// A<T>() returns a matcher that matches any value of type T. +template <typename T> +Matcher<T> A(); + +// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION +// and MUST NOT BE USED IN USER CODE!!! +namespace internal { + +// If the explanation is not empty, prints it to the ostream. +inline void PrintIfNotEmpty(const internal::string& explanation, + ::std::ostream* os) { + if (explanation != "" && os != NULL) { + *os << ", " << explanation; + } +} + +// Returns true if the given type name is easy to read by a human. +// This is used to decide whether printing the type of a value might +// be helpful. +inline bool IsReadableTypeName(const string& type_name) { + // We consider a type name readable if it's short or doesn't contain + // a template or function type. + return (type_name.length() <= 20 || + type_name.find_first_of("<(") == string::npos); +} + +// Matches the value against the given matcher, prints the value and explains +// the match result to the listener. Returns the match result. +// 'listener' must not be NULL. +// Value cannot be passed by const reference, because some matchers take a +// non-const argument. +template <typename Value, typename T> +bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher, + MatchResultListener* listener) { + if (!listener->IsInterested()) { + // If the listener is not interested, we do not need to construct the + // inner explanation. + return matcher.Matches(value); + } + + StringMatchResultListener inner_listener; + const bool match = matcher.MatchAndExplain(value, &inner_listener); + + UniversalPrint(value, listener->stream()); +#if GTEST_HAS_RTTI + const string& type_name = GetTypeName<Value>(); + if (IsReadableTypeName(type_name)) + *listener->stream() << " (of type " << type_name << ")"; +#endif + PrintIfNotEmpty(inner_listener.str(), listener->stream()); + + return match; +} + +// An internal helper class for doing compile-time loop on a tuple's +// fields. +template <size_t N> +class TuplePrefix { + public: + // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true + // iff the first N fields of matcher_tuple matches the first N + // fields of value_tuple, respectively. + template <typename MatcherTuple, typename ValueTuple> + static bool Matches(const MatcherTuple& matcher_tuple, + const ValueTuple& value_tuple) { + return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) + && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple)); + } + + // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os) + // describes failures in matching the first N fields of matchers + // against the first N fields of values. If there is no failure, + // nothing will be streamed to os. + template <typename MatcherTuple, typename ValueTuple> + static void ExplainMatchFailuresTo(const MatcherTuple& matchers, + const ValueTuple& values, + ::std::ostream* os) { + // First, describes failures in the first N - 1 fields. + TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os); + + // Then describes the failure (if any) in the (N - 1)-th (0-based) + // field. + typename tuple_element<N - 1, MatcherTuple>::type matcher = + get<N - 1>(matchers); + typedef typename tuple_element<N - 1, ValueTuple>::type Value; + Value value = get<N - 1>(values); + StringMatchResultListener listener; + if (!matcher.MatchAndExplain(value, &listener)) { + // TODO(wan): include in the message the name of the parameter + // as used in MOCK_METHOD*() when possible. + *os << " Expected arg #" << N - 1 << ": "; + get<N - 1>(matchers).DescribeTo(os); + *os << "\n Actual: "; + // We remove the reference in type Value to prevent the + // universal printer from printing the address of value, which + // isn't interesting to the user most of the time. The + // matcher's MatchAndExplain() method handles the case when + // the address is interesting. + internal::UniversalPrint(value, os); + PrintIfNotEmpty(listener.str(), os); + *os << "\n"; + } + } +}; + +// The base case. +template <> +class TuplePrefix<0> { + public: + template <typename MatcherTuple, typename ValueTuple> + static bool Matches(const MatcherTuple& /* matcher_tuple */, + const ValueTuple& /* value_tuple */) { + return true; + } + + template <typename MatcherTuple, typename ValueTuple> + static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */, + const ValueTuple& /* values */, + ::std::ostream* /* os */) {} +}; + +// TupleMatches(matcher_tuple, value_tuple) returns true iff all +// matchers in matcher_tuple match the corresponding fields in +// value_tuple. It is a compiler error if matcher_tuple and +// value_tuple have different number of fields or incompatible field +// types. +template <typename MatcherTuple, typename ValueTuple> +bool TupleMatches(const MatcherTuple& matcher_tuple, + const ValueTuple& value_tuple) { + // Makes sure that matcher_tuple and value_tuple have the same + // number of fields. + GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value == + tuple_size<ValueTuple>::value, + matcher_and_value_have_different_numbers_of_fields); + return TuplePrefix<tuple_size<ValueTuple>::value>:: + Matches(matcher_tuple, value_tuple); +} + +// Describes failures in matching matchers against values. If there +// is no failure, nothing will be streamed to os. +template <typename MatcherTuple, typename ValueTuple> +void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, + const ValueTuple& values, + ::std::ostream* os) { + TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo( + matchers, values, os); +} + +// TransformTupleValues and its helper. +// +// TransformTupleValuesHelper hides the internal machinery that +// TransformTupleValues uses to implement a tuple traversal. +template <typename Tuple, typename Func, typename OutIter> +class TransformTupleValuesHelper { + private: + typedef ::testing::tuple_size<Tuple> TupleSize; + + public: + // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'. + // Returns the final value of 'out' in case the caller needs it. + static OutIter Run(Func f, const Tuple& t, OutIter out) { + return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out); + } + + private: + template <typename Tup, size_t kRemainingSize> + struct IterateOverTuple { + OutIter operator() (Func f, const Tup& t, OutIter out) const { + *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t)); + return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out); + } + }; + template <typename Tup> + struct IterateOverTuple<Tup, 0> { + OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const { + return out; + } + }; +}; + +// Successively invokes 'f(element)' on each element of the tuple 't', +// appending each result to the 'out' iterator. Returns the final value +// of 'out'. +template <typename Tuple, typename Func, typename OutIter> +OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) { + return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out); +} + +// Implements A<T>(). +template <typename T> +class AnyMatcherImpl : public MatcherInterface<T> { + public: + virtual bool MatchAndExplain( + T /* x */, MatchResultListener* /* listener */) const { return true; } + virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; } + virtual void DescribeNegationTo(::std::ostream* os) const { + // This is mostly for completeness' safe, as it's not very useful + // to write Not(A<bool>()). However we cannot completely rule out + // such a possibility, and it doesn't hurt to be prepared. + *os << "never matches"; + } +}; + +// Implements _, a matcher that matches any value of any +// type. This is a polymorphic matcher, so we need a template type +// conversion operator to make it appearing as a Matcher<T> for any +// type T. +class AnythingMatcher { + public: + template <typename T> + operator Matcher<T>() const { return A<T>(); } +}; + +// Implements a matcher that compares a given value with a +// pre-supplied value using one of the ==, <=, <, etc, operators. The +// two values being compared don't have to have the same type. +// +// The matcher defined here is polymorphic (for example, Eq(5) can be +// used to match an int, a short, a double, etc). Therefore we use +// a template type conversion operator in the implementation. +// +// The following template definition assumes that the Rhs parameter is +// a "bare" type (i.e. neither 'const T' nor 'T&'). +template <typename D, typename Rhs, typename Op> +class ComparisonBase { + public: + explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {} + template <typename Lhs> + operator Matcher<Lhs>() const { + return MakeMatcher(new Impl<Lhs>(rhs_)); + } + + private: + template <typename Lhs> + class Impl : public MatcherInterface<Lhs> { + public: + explicit Impl(const Rhs& rhs) : rhs_(rhs) {} + virtual bool MatchAndExplain( + Lhs lhs, MatchResultListener* /* listener */) const { + return Op()(lhs, rhs_); + } + virtual void DescribeTo(::std::ostream* os) const { + *os << D::Desc() << " "; + UniversalPrint(rhs_, os); + } + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << D::NegatedDesc() << " "; + UniversalPrint(rhs_, os); + } + private: + Rhs rhs_; + GTEST_DISALLOW_ASSIGN_(Impl); + }; + Rhs rhs_; + GTEST_DISALLOW_ASSIGN_(ComparisonBase); +}; + +template <typename Rhs> +class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> { + public: + explicit EqMatcher(const Rhs& rhs) + : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { } + static const char* Desc() { return "is equal to"; } + static const char* NegatedDesc() { return "isn't equal to"; } +}; +template <typename Rhs> +class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> { + public: + explicit NeMatcher(const Rhs& rhs) + : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { } + static const char* Desc() { return "isn't equal to"; } + static const char* NegatedDesc() { return "is equal to"; } +}; +template <typename Rhs> +class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> { + public: + explicit LtMatcher(const Rhs& rhs) + : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { } + static const char* Desc() { return "is <"; } + static const char* NegatedDesc() { return "isn't <"; } +}; +template <typename Rhs> +class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> { + public: + explicit GtMatcher(const Rhs& rhs) + : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { } + static const char* Desc() { return "is >"; } + static const char* NegatedDesc() { return "isn't >"; } +}; +template <typename Rhs> +class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> { + public: + explicit LeMatcher(const Rhs& rhs) + : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { } + static const char* Desc() { return "is <="; } + static const char* NegatedDesc() { return "isn't <="; } +}; +template <typename Rhs> +class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> { + public: + explicit GeMatcher(const Rhs& rhs) + : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { } + static const char* Desc() { return "is >="; } + static const char* NegatedDesc() { return "isn't >="; } +}; + +// Implements the polymorphic IsNull() matcher, which matches any raw or smart +// pointer that is NULL. +class IsNullMatcher { + public: + template <typename Pointer> + bool MatchAndExplain(const Pointer& p, + MatchResultListener* /* listener */) const { +#if GTEST_LANG_CXX11 + return p == nullptr; +#else // GTEST_LANG_CXX11 + return GetRawPointer(p) == NULL; +#endif // GTEST_LANG_CXX11 + } + + void DescribeTo(::std::ostream* os) const { *os << "is NULL"; } + void DescribeNegationTo(::std::ostream* os) const { + *os << "isn't NULL"; + } +}; + +// Implements the polymorphic NotNull() matcher, which matches any raw or smart +// pointer that is not NULL. +class NotNullMatcher { + public: + template <typename Pointer> + bool MatchAndExplain(const Pointer& p, + MatchResultListener* /* listener */) const { +#if GTEST_LANG_CXX11 + return p != nullptr; +#else // GTEST_LANG_CXX11 + return GetRawPointer(p) != NULL; +#endif // GTEST_LANG_CXX11 + } + + void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; } + void DescribeNegationTo(::std::ostream* os) const { + *os << "is NULL"; + } +}; + +// Ref(variable) matches any argument that is a reference to +// 'variable'. This matcher is polymorphic as it can match any +// super type of the type of 'variable'. +// +// The RefMatcher template class implements Ref(variable). It can +// only be instantiated with a reference type. This prevents a user +// from mistakenly using Ref(x) to match a non-reference function +// argument. For example, the following will righteously cause a +// compiler error: +// +// int n; +// Matcher<int> m1 = Ref(n); // This won't compile. +// Matcher<int&> m2 = Ref(n); // This will compile. +template <typename T> +class RefMatcher; + +template <typename T> +class RefMatcher<T&> { + // Google Mock is a generic framework and thus needs to support + // mocking any function types, including those that take non-const + // reference arguments. Therefore the template parameter T (and + // Super below) can be instantiated to either a const type or a + // non-const type. + public: + // RefMatcher() takes a T& instead of const T&, as we want the + // compiler to catch using Ref(const_value) as a matcher for a + // non-const reference. + explicit RefMatcher(T& x) : object_(x) {} // NOLINT + + template <typename Super> + operator Matcher<Super&>() const { + // By passing object_ (type T&) to Impl(), which expects a Super&, + // we make sure that Super is a super type of T. In particular, + // this catches using Ref(const_value) as a matcher for a + // non-const reference, as you cannot implicitly convert a const + // reference to a non-const reference. + return MakeMatcher(new Impl<Super>(object_)); + } + + private: + template <typename Super> + class Impl : public MatcherInterface<Super&> { + public: + explicit Impl(Super& x) : object_(x) {} // NOLINT + + // MatchAndExplain() takes a Super& (as opposed to const Super&) + // in order to match the interface MatcherInterface<Super&>. + virtual bool MatchAndExplain( + Super& x, MatchResultListener* listener) const { + *listener << "which is located @" << static_cast<const void*>(&x); + return &x == &object_; + } + + virtual void DescribeTo(::std::ostream* os) const { + *os << "references the variable "; + UniversalPrinter<Super&>::Print(object_, os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "does not reference the variable "; + UniversalPrinter<Super&>::Print(object_, os); + } + + private: + const Super& object_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + T& object_; + + GTEST_DISALLOW_ASSIGN_(RefMatcher); +}; + +// Polymorphic helper functions for narrow and wide string matchers. +inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { + return String::CaseInsensitiveCStringEquals(lhs, rhs); +} + +inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs, + const wchar_t* rhs) { + return String::CaseInsensitiveWideCStringEquals(lhs, rhs); +} + +// String comparison for narrow or wide strings that can have embedded NUL +// characters. +template <typename StringType> +bool CaseInsensitiveStringEquals(const StringType& s1, + const StringType& s2) { + // Are the heads equal? + if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) { + return false; + } + + // Skip the equal heads. + const typename StringType::value_type nul = 0; + const size_t i1 = s1.find(nul), i2 = s2.find(nul); + + // Are we at the end of either s1 or s2? + if (i1 == StringType::npos || i2 == StringType::npos) { + return i1 == i2; + } + + // Are the tails equal? + return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1)); +} + +// String matchers. + +// Implements equality-based string matchers like StrEq, StrCaseNe, and etc. +template <typename StringType> +class StrEqualityMatcher { + public: + StrEqualityMatcher(const StringType& str, bool expect_eq, + bool case_sensitive) + : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {} + + // Accepts pointer types, particularly: + // const char* + // char* + // const wchar_t* + // wchar_t* + template <typename CharType> + bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { + if (s == NULL) { + return !expect_eq_; + } + return MatchAndExplain(StringType(s), listener); + } + + // Matches anything that can convert to StringType. + // + // This is a template, not just a plain function with const StringType&, + // because StringPiece has some interfering non-explicit constructors. + template <typename MatcheeStringType> + bool MatchAndExplain(const MatcheeStringType& s, + MatchResultListener* /* listener */) const { + const StringType& s2(s); + const bool eq = case_sensitive_ ? s2 == string_ : + CaseInsensitiveStringEquals(s2, string_); + return expect_eq_ == eq; + } + + void DescribeTo(::std::ostream* os) const { + DescribeToHelper(expect_eq_, os); + } + + void DescribeNegationTo(::std::ostream* os) const { + DescribeToHelper(!expect_eq_, os); + } + + private: + void DescribeToHelper(bool expect_eq, ::std::ostream* os) const { + *os << (expect_eq ? "is " : "isn't "); + *os << "equal to "; + if (!case_sensitive_) { + *os << "(ignoring case) "; + } + UniversalPrint(string_, os); + } + + const StringType string_; + const bool expect_eq_; + const bool case_sensitive_; + + GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher); +}; + +// Implements the polymorphic HasSubstr(substring) matcher, which +// can be used as a Matcher<T> as long as T can be converted to a +// string. +template <typename StringType> +class HasSubstrMatcher { + public: + explicit HasSubstrMatcher(const StringType& substring) + : substring_(substring) {} + + // Accepts pointer types, particularly: + // const char* + // char* + // const wchar_t* + // wchar_t* + template <typename CharType> + bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { + return s != NULL && MatchAndExplain(StringType(s), listener); + } + + // Matches anything that can convert to StringType. + // + // This is a template, not just a plain function with const StringType&, + // because StringPiece has some interfering non-explicit constructors. + template <typename MatcheeStringType> + bool MatchAndExplain(const MatcheeStringType& s, + MatchResultListener* /* listener */) const { + const StringType& s2(s); + return s2.find(substring_) != StringType::npos; + } + + // Describes what this matcher matches. + void DescribeTo(::std::ostream* os) const { + *os << "has substring "; + UniversalPrint(substring_, os); + } + + void DescribeNegationTo(::std::ostream* os) const { + *os << "has no substring "; + UniversalPrint(substring_, os); + } + + private: + const StringType substring_; + + GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher); +}; + +// Implements the polymorphic StartsWith(substring) matcher, which +// can be used as a Matcher<T> as long as T can be converted to a +// string. +template <typename StringType> +class StartsWithMatcher { + public: + explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) { + } + + // Accepts pointer types, particularly: + // const char* + // char* + // const wchar_t* + // wchar_t* + template <typename CharType> + bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { + return s != NULL && MatchAndExplain(StringType(s), listener); + } + + // Matches anything that can convert to StringType. + // + // This is a template, not just a plain function with const StringType&, + // because StringPiece has some interfering non-explicit constructors. + template <typename MatcheeStringType> + bool MatchAndExplain(const MatcheeStringType& s, + MatchResultListener* /* listener */) const { + const StringType& s2(s); + return s2.length() >= prefix_.length() && + s2.substr(0, prefix_.length()) == prefix_; + } + + void DescribeTo(::std::ostream* os) const { + *os << "starts with "; + UniversalPrint(prefix_, os); + } + + void DescribeNegationTo(::std::ostream* os) const { + *os << "doesn't start with "; + UniversalPrint(prefix_, os); + } + + private: + const StringType prefix_; + + GTEST_DISALLOW_ASSIGN_(StartsWithMatcher); +}; + +// Implements the polymorphic EndsWith(substring) matcher, which +// can be used as a Matcher<T> as long as T can be converted to a +// string. +template <typename StringType> +class EndsWithMatcher { + public: + explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {} + + // Accepts pointer types, particularly: + // const char* + // char* + // const wchar_t* + // wchar_t* + template <typename CharType> + bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { + return s != NULL && MatchAndExplain(StringType(s), listener); + } + + // Matches anything that can convert to StringType. + // + // This is a template, not just a plain function with const StringType&, + // because StringPiece has some interfering non-explicit constructors. + template <typename MatcheeStringType> + bool MatchAndExplain(const MatcheeStringType& s, + MatchResultListener* /* listener */) const { + const StringType& s2(s); + return s2.length() >= suffix_.length() && + s2.substr(s2.length() - suffix_.length()) == suffix_; + } + + void DescribeTo(::std::ostream* os) const { + *os << "ends with "; + UniversalPrint(suffix_, os); + } + + void DescribeNegationTo(::std::ostream* os) const { + *os << "doesn't end with "; + UniversalPrint(suffix_, os); + } + + private: + const StringType suffix_; + + GTEST_DISALLOW_ASSIGN_(EndsWithMatcher); +}; + +// Implements polymorphic matchers MatchesRegex(regex) and +// ContainsRegex(regex), which can be used as a Matcher<T> as long as +// T can be converted to a string. +class MatchesRegexMatcher { + public: + MatchesRegexMatcher(const RE* regex, bool full_match) + : regex_(regex), full_match_(full_match) {} + + // Accepts pointer types, particularly: + // const char* + // char* + // const wchar_t* + // wchar_t* + template <typename CharType> + bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { + return s != NULL && MatchAndExplain(internal::string(s), listener); + } + + // Matches anything that can convert to internal::string. + // + // This is a template, not just a plain function with const internal::string&, + // because StringPiece has some interfering non-explicit constructors. + template <class MatcheeStringType> + bool MatchAndExplain(const MatcheeStringType& s, + MatchResultListener* /* listener */) const { + const internal::string& s2(s); + return full_match_ ? RE::FullMatch(s2, *regex_) : + RE::PartialMatch(s2, *regex_); + } + + void DescribeTo(::std::ostream* os) const { + *os << (full_match_ ? "matches" : "contains") + << " regular expression "; + UniversalPrinter<internal::string>::Print(regex_->pattern(), os); + } + + void DescribeNegationTo(::std::ostream* os) const { + *os << "doesn't " << (full_match_ ? "match" : "contain") + << " regular expression "; + UniversalPrinter<internal::string>::Print(regex_->pattern(), os); + } + + private: + const internal::linked_ptr<const RE> regex_; + const bool full_match_; + + GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher); +}; + +// Implements a matcher that compares the two fields of a 2-tuple +// using one of the ==, <=, <, etc, operators. The two fields being +// compared don't have to have the same type. +// +// The matcher defined here is polymorphic (for example, Eq() can be +// used to match a tuple<int, short>, a tuple<const long&, double>, +// etc). Therefore we use a template type conversion operator in the +// implementation. +template <typename D, typename Op> +class PairMatchBase { + public: + template <typename T1, typename T2> + operator Matcher< ::testing::tuple<T1, T2> >() const { + return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >); + } + template <typename T1, typename T2> + operator Matcher<const ::testing::tuple<T1, T2>&>() const { + return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>); + } + + private: + static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT + return os << D::Desc(); + } + + template <typename Tuple> + class Impl : public MatcherInterface<Tuple> { + public: + virtual bool MatchAndExplain( + Tuple args, + MatchResultListener* /* listener */) const { + return Op()(::testing::get<0>(args), ::testing::get<1>(args)); + } + virtual void DescribeTo(::std::ostream* os) const { + *os << "are " << GetDesc; + } + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "aren't " << GetDesc; + } + }; +}; + +class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> { + public: + static const char* Desc() { return "an equal pair"; } +}; +class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> { + public: + static const char* Desc() { return "an unequal pair"; } +}; +class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> { + public: + static const char* Desc() { return "a pair where the first < the second"; } +}; +class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> { + public: + static const char* Desc() { return "a pair where the first > the second"; } +}; +class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> { + public: + static const char* Desc() { return "a pair where the first <= the second"; } +}; +class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> { + public: + static const char* Desc() { return "a pair where the first >= the second"; } +}; + +// Implements the Not(...) matcher for a particular argument type T. +// We do not nest it inside the NotMatcher class template, as that +// will prevent different instantiations of NotMatcher from sharing +// the same NotMatcherImpl<T> class. +template <typename T> +class NotMatcherImpl : public MatcherInterface<T> { + public: + explicit NotMatcherImpl(const Matcher<T>& matcher) + : matcher_(matcher) {} + + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + return !matcher_.MatchAndExplain(x, listener); + } + + virtual void DescribeTo(::std::ostream* os) const { + matcher_.DescribeNegationTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + matcher_.DescribeTo(os); + } + + private: + const Matcher<T> matcher_; + + GTEST_DISALLOW_ASSIGN_(NotMatcherImpl); +}; + +// Implements the Not(m) matcher, which matches a value that doesn't +// match matcher m. +template <typename InnerMatcher> +class NotMatcher { + public: + explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {} + + // This template type conversion operator allows Not(m) to be used + // to match any type m can match. + template <typename T> + operator Matcher<T>() const { + return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_))); + } + + private: + InnerMatcher matcher_; + + GTEST_DISALLOW_ASSIGN_(NotMatcher); +}; + +// Implements the AllOf(m1, m2) matcher for a particular argument type +// T. We do not nest it inside the BothOfMatcher class template, as +// that will prevent different instantiations of BothOfMatcher from +// sharing the same BothOfMatcherImpl<T> class. +template <typename T> +class BothOfMatcherImpl : public MatcherInterface<T> { + public: + BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2) + : matcher1_(matcher1), matcher2_(matcher2) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "("; + matcher1_.DescribeTo(os); + *os << ") and ("; + matcher2_.DescribeTo(os); + *os << ")"; + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "("; + matcher1_.DescribeNegationTo(os); + *os << ") or ("; + matcher2_.DescribeNegationTo(os); + *os << ")"; + } + + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + // If either matcher1_ or matcher2_ doesn't match x, we only need + // to explain why one of them fails. + StringMatchResultListener listener1; + if (!matcher1_.MatchAndExplain(x, &listener1)) { + *listener << listener1.str(); + return false; + } + + StringMatchResultListener listener2; + if (!matcher2_.MatchAndExplain(x, &listener2)) { + *listener << listener2.str(); + return false; + } + + // Otherwise we need to explain why *both* of them match. + const internal::string s1 = listener1.str(); + const internal::string s2 = listener2.str(); + + if (s1 == "") { + *listener << s2; + } else { + *listener << s1; + if (s2 != "") { + *listener << ", and " << s2; + } + } + return true; + } + + private: + const Matcher<T> matcher1_; + const Matcher<T> matcher2_; + + GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl); +}; + +#if GTEST_LANG_CXX11 +// MatcherList provides mechanisms for storing a variable number of matchers in +// a list structure (ListType) and creating a combining matcher from such a +// list. +// The template is defined recursively using the following template paramters: +// * kSize is the length of the MatcherList. +// * Head is the type of the first matcher of the list. +// * Tail denotes the types of the remaining matchers of the list. +template <int kSize, typename Head, typename... Tail> +struct MatcherList { + typedef MatcherList<kSize - 1, Tail...> MatcherListTail; + typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType; + + // BuildList stores variadic type values in a nested pair structure. + // Example: + // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return + // the corresponding result of type pair<int, pair<string, float>>. + static ListType BuildList(const Head& matcher, const Tail&... tail) { + return ListType(matcher, MatcherListTail::BuildList(tail...)); + } + + // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built + // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the + // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a + // constructor taking two Matcher<T>s as input. + template <typename T, template <typename /* T */> class CombiningMatcher> + static Matcher<T> CreateMatcher(const ListType& matchers) { + return Matcher<T>(new CombiningMatcher<T>( + SafeMatcherCast<T>(matchers.first), + MatcherListTail::template CreateMatcher<T, CombiningMatcher>( + matchers.second))); + } +}; + +// The following defines the base case for the recursive definition of +// MatcherList. +template <typename Matcher1, typename Matcher2> +struct MatcherList<2, Matcher1, Matcher2> { + typedef ::std::pair<Matcher1, Matcher2> ListType; + + static ListType BuildList(const Matcher1& matcher1, + const Matcher2& matcher2) { + return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2); + } + + template <typename T, template <typename /* T */> class CombiningMatcher> + static Matcher<T> CreateMatcher(const ListType& matchers) { + return Matcher<T>(new CombiningMatcher<T>( + SafeMatcherCast<T>(matchers.first), + SafeMatcherCast<T>(matchers.second))); + } +}; + +// VariadicMatcher is used for the variadic implementation of +// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...). +// CombiningMatcher<T> is used to recursively combine the provided matchers +// (of type Args...). +template <template <typename T> class CombiningMatcher, typename... Args> +class VariadicMatcher { + public: + VariadicMatcher(const Args&... matchers) // NOLINT + : matchers_(MatcherListType::BuildList(matchers...)) {} + + // This template type conversion operator allows an + // VariadicMatcher<Matcher1, Matcher2...> object to match any type that + // all of the provided matchers (Matcher1, Matcher2, ...) can match. + template <typename T> + operator Matcher<T>() const { + return MatcherListType::template CreateMatcher<T, CombiningMatcher>( + matchers_); + } + + private: + typedef MatcherList<sizeof...(Args), Args...> MatcherListType; + + const typename MatcherListType::ListType matchers_; + + GTEST_DISALLOW_ASSIGN_(VariadicMatcher); +}; + +template <typename... Args> +using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>; + +#endif // GTEST_LANG_CXX11 + +// Used for implementing the AllOf(m_1, ..., m_n) matcher, which +// matches a value that matches all of the matchers m_1, ..., and m_n. +template <typename Matcher1, typename Matcher2> +class BothOfMatcher { + public: + BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2) + : matcher1_(matcher1), matcher2_(matcher2) {} + + // This template type conversion operator allows a + // BothOfMatcher<Matcher1, Matcher2> object to match any type that + // both Matcher1 and Matcher2 can match. + template <typename T> + operator Matcher<T>() const { + return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_), + SafeMatcherCast<T>(matcher2_))); + } + + private: + Matcher1 matcher1_; + Matcher2 matcher2_; + + GTEST_DISALLOW_ASSIGN_(BothOfMatcher); +}; + +// Implements the AnyOf(m1, m2) matcher for a particular argument type +// T. We do not nest it inside the AnyOfMatcher class template, as +// that will prevent different instantiations of AnyOfMatcher from +// sharing the same EitherOfMatcherImpl<T> class. +template <typename T> +class EitherOfMatcherImpl : public MatcherInterface<T> { + public: + EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2) + : matcher1_(matcher1), matcher2_(matcher2) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "("; + matcher1_.DescribeTo(os); + *os << ") or ("; + matcher2_.DescribeTo(os); + *os << ")"; + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "("; + matcher1_.DescribeNegationTo(os); + *os << ") and ("; + matcher2_.DescribeNegationTo(os); + *os << ")"; + } + + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + // If either matcher1_ or matcher2_ matches x, we just need to + // explain why *one* of them matches. + StringMatchResultListener listener1; + if (matcher1_.MatchAndExplain(x, &listener1)) { + *listener << listener1.str(); + return true; + } + + StringMatchResultListener listener2; + if (matcher2_.MatchAndExplain(x, &listener2)) { + *listener << listener2.str(); + return true; + } + + // Otherwise we need to explain why *both* of them fail. + const internal::string s1 = listener1.str(); + const internal::string s2 = listener2.str(); + + if (s1 == "") { + *listener << s2; + } else { + *listener << s1; + if (s2 != "") { + *listener << ", and " << s2; + } + } + return false; + } + + private: + const Matcher<T> matcher1_; + const Matcher<T> matcher2_; + + GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl); +}; + +#if GTEST_LANG_CXX11 +// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...). +template <typename... Args> +using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>; + +#endif // GTEST_LANG_CXX11 + +// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which +// matches a value that matches at least one of the matchers m_1, ..., +// and m_n. +template <typename Matcher1, typename Matcher2> +class EitherOfMatcher { + public: + EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2) + : matcher1_(matcher1), matcher2_(matcher2) {} + + // This template type conversion operator allows a + // EitherOfMatcher<Matcher1, Matcher2> object to match any type that + // both Matcher1 and Matcher2 can match. + template <typename T> + operator Matcher<T>() const { + return Matcher<T>(new EitherOfMatcherImpl<T>( + SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_))); + } + + private: + Matcher1 matcher1_; + Matcher2 matcher2_; + + GTEST_DISALLOW_ASSIGN_(EitherOfMatcher); +}; + +// Used for implementing Truly(pred), which turns a predicate into a +// matcher. +template <typename Predicate> +class TrulyMatcher { + public: + explicit TrulyMatcher(Predicate pred) : predicate_(pred) {} + + // This method template allows Truly(pred) to be used as a matcher + // for type T where T is the argument type of predicate 'pred'. The + // argument is passed by reference as the predicate may be + // interested in the address of the argument. + template <typename T> + bool MatchAndExplain(T& x, // NOLINT + MatchResultListener* /* listener */) const { + // Without the if-statement, MSVC sometimes warns about converting + // a value to bool (warning 4800). + // + // We cannot write 'return !!predicate_(x);' as that doesn't work + // when predicate_(x) returns a class convertible to bool but + // having no operator!(). + if (predicate_(x)) + return true; + return false; + } + + void DescribeTo(::std::ostream* os) const { + *os << "satisfies the given predicate"; + } + + void DescribeNegationTo(::std::ostream* os) const { + *os << "doesn't satisfy the given predicate"; + } + + private: + Predicate predicate_; + + GTEST_DISALLOW_ASSIGN_(TrulyMatcher); +}; + +// Used for implementing Matches(matcher), which turns a matcher into +// a predicate. +template <typename M> +class MatcherAsPredicate { + public: + explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {} + + // This template operator() allows Matches(m) to be used as a + // predicate on type T where m is a matcher on type T. + // + // The argument x is passed by reference instead of by value, as + // some matcher may be interested in its address (e.g. as in + // Matches(Ref(n))(x)). + template <typename T> + bool operator()(const T& x) const { + // We let matcher_ commit to a particular type here instead of + // when the MatcherAsPredicate object was constructed. This + // allows us to write Matches(m) where m is a polymorphic matcher + // (e.g. Eq(5)). + // + // If we write Matcher<T>(matcher_).Matches(x) here, it won't + // compile when matcher_ has type Matcher<const T&>; if we write + // Matcher<const T&>(matcher_).Matches(x) here, it won't compile + // when matcher_ has type Matcher<T>; if we just write + // matcher_.Matches(x), it won't compile when matcher_ is + // polymorphic, e.g. Eq(5). + // + // MatcherCast<const T&>() is necessary for making the code work + // in all of the above situations. + return MatcherCast<const T&>(matcher_).Matches(x); + } + + private: + M matcher_; + + GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate); +}; + +// For implementing ASSERT_THAT() and EXPECT_THAT(). The template +// argument M must be a type that can be converted to a matcher. +template <typename M> +class PredicateFormatterFromMatcher { + public: + explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {} + + // This template () operator allows a PredicateFormatterFromMatcher + // object to act as a predicate-formatter suitable for using with + // Google Test's EXPECT_PRED_FORMAT1() macro. + template <typename T> + AssertionResult operator()(const char* value_text, const T& x) const { + // We convert matcher_ to a Matcher<const T&> *now* instead of + // when the PredicateFormatterFromMatcher object was constructed, + // as matcher_ may be polymorphic (e.g. NotNull()) and we won't + // know which type to instantiate it to until we actually see the + // type of x here. + // + // We write SafeMatcherCast<const T&>(matcher_) instead of + // Matcher<const T&>(matcher_), as the latter won't compile when + // matcher_ has type Matcher<T> (e.g. An<int>()). + // We don't write MatcherCast<const T&> either, as that allows + // potentially unsafe downcasting of the matcher argument. + const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_); + StringMatchResultListener listener; + if (MatchPrintAndExplain(x, matcher, &listener)) + return AssertionSuccess(); + + ::std::stringstream ss; + ss << "Value of: " << value_text << "\n" + << "Expected: "; + matcher.DescribeTo(&ss); + ss << "\n Actual: " << listener.str(); + return AssertionFailure() << ss.str(); + } + + private: + const M matcher_; + + GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher); +}; + +// A helper function for converting a matcher to a predicate-formatter +// without the user needing to explicitly write the type. This is +// used for implementing ASSERT_THAT() and EXPECT_THAT(). +// Implementation detail: 'matcher' is received by-value to force decaying. +template <typename M> +inline PredicateFormatterFromMatcher<M> +MakePredicateFormatterFromMatcher(M matcher) { + return PredicateFormatterFromMatcher<M>(internal::move(matcher)); +} + +// Implements the polymorphic floating point equality matcher, which matches +// two float values using ULP-based approximation or, optionally, a +// user-specified epsilon. The template is meant to be instantiated with +// FloatType being either float or double. +template <typename FloatType> +class FloatingEqMatcher { + public: + // Constructor for FloatingEqMatcher. + // The matcher's input will be compared with expected. The matcher treats two + // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards, + // equality comparisons between NANs will always return false. We specify a + // negative max_abs_error_ term to indicate that ULP-based approximation will + // be used for comparison. + FloatingEqMatcher(FloatType expected, bool nan_eq_nan) : + expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) { + } + + // Constructor that supports a user-specified max_abs_error that will be used + // for comparison instead of ULP-based approximation. The max absolute + // should be non-negative. + FloatingEqMatcher(FloatType expected, bool nan_eq_nan, + FloatType max_abs_error) + : expected_(expected), + nan_eq_nan_(nan_eq_nan), + max_abs_error_(max_abs_error) { + GTEST_CHECK_(max_abs_error >= 0) + << ", where max_abs_error is" << max_abs_error; + } + + // Implements floating point equality matcher as a Matcher<T>. + template <typename T> + class Impl : public MatcherInterface<T> { + public: + Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error) + : expected_(expected), + nan_eq_nan_(nan_eq_nan), + max_abs_error_(max_abs_error) {} + + virtual bool MatchAndExplain(T value, + MatchResultListener* listener) const { + const FloatingPoint<FloatType> actual(value), expected(expected_); + + // Compares NaNs first, if nan_eq_nan_ is true. + if (actual.is_nan() || expected.is_nan()) { + if (actual.is_nan() && expected.is_nan()) { + return nan_eq_nan_; + } + // One is nan; the other is not nan. + return false; + } + if (HasMaxAbsError()) { + // We perform an equality check so that inf will match inf, regardless + // of error bounds. If the result of value - expected_ would result in + // overflow or if either value is inf, the default result is infinity, + // which should only match if max_abs_error_ is also infinity. + if (value == expected_) { + return true; + } + + const FloatType diff = value - expected_; + if (fabs(diff) <= max_abs_error_) { + return true; + } + + if (listener->IsInterested()) { + *listener << "which is " << diff << " from " << expected_; + } + return false; + } else { + return actual.AlmostEquals(expected); + } + } + + virtual void DescribeTo(::std::ostream* os) const { + // os->precision() returns the previously set precision, which we + // store to restore the ostream to its original configuration + // after outputting. + const ::std::streamsize old_precision = os->precision( + ::std::numeric_limits<FloatType>::digits10 + 2); + if (FloatingPoint<FloatType>(expected_).is_nan()) { + if (nan_eq_nan_) { + *os << "is NaN"; + } else { + *os << "never matches"; + } + } else { + *os << "is approximately " << expected_; + if (HasMaxAbsError()) { + *os << " (absolute error <= " << max_abs_error_ << ")"; + } + } + os->precision(old_precision); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + // As before, get original precision. + const ::std::streamsize old_precision = os->precision( + ::std::numeric_limits<FloatType>::digits10 + 2); + if (FloatingPoint<FloatType>(expected_).is_nan()) { + if (nan_eq_nan_) { + *os << "isn't NaN"; + } else { + *os << "is anything"; + } + } else { + *os << "isn't approximately " << expected_; + if (HasMaxAbsError()) { + *os << " (absolute error > " << max_abs_error_ << ")"; + } + } + // Restore original precision. + os->precision(old_precision); + } + + private: + bool HasMaxAbsError() const { + return max_abs_error_ >= 0; + } + + const FloatType expected_; + const bool nan_eq_nan_; + // max_abs_error will be used for value comparison when >= 0. + const FloatType max_abs_error_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + // The following 3 type conversion operators allow FloatEq(expected) and + // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a + // Matcher<const float&>, or a Matcher<float&>, but nothing else. + // (While Google's C++ coding style doesn't allow arguments passed + // by non-const reference, we may see them in code not conforming to + // the style. Therefore Google Mock needs to support them.) + operator Matcher<FloatType>() const { + return MakeMatcher( + new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_)); + } + + operator Matcher<const FloatType&>() const { + return MakeMatcher( + new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_)); + } + + operator Matcher<FloatType&>() const { + return MakeMatcher( + new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_)); + } + + private: + const FloatType expected_; + const bool nan_eq_nan_; + // max_abs_error will be used for value comparison when >= 0. + const FloatType max_abs_error_; + + GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher); +}; + +// Implements the Pointee(m) matcher for matching a pointer whose +// pointee matches matcher m. The pointer can be either raw or smart. +template <typename InnerMatcher> +class PointeeMatcher { + public: + explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {} + + // This type conversion operator template allows Pointee(m) to be + // used as a matcher for any pointer type whose pointee type is + // compatible with the inner matcher, where type Pointer can be + // either a raw pointer or a smart pointer. + // + // The reason we do this instead of relying on + // MakePolymorphicMatcher() is that the latter is not flexible + // enough for implementing the DescribeTo() method of Pointee(). + template <typename Pointer> + operator Matcher<Pointer>() const { + return MakeMatcher(new Impl<Pointer>(matcher_)); + } + + private: + // The monomorphic implementation that works for a particular pointer type. + template <typename Pointer> + class Impl : public MatcherInterface<Pointer> { + public: + typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT + GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee; + + explicit Impl(const InnerMatcher& matcher) + : matcher_(MatcherCast<const Pointee&>(matcher)) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "points to a value that "; + matcher_.DescribeTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "does not point to a value that "; + matcher_.DescribeTo(os); + } + + virtual bool MatchAndExplain(Pointer pointer, + MatchResultListener* listener) const { + if (GetRawPointer(pointer) == NULL) + return false; + + *listener << "which points to "; + return MatchPrintAndExplain(*pointer, matcher_, listener); + } + + private: + const Matcher<const Pointee&> matcher_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + const InnerMatcher matcher_; + + GTEST_DISALLOW_ASSIGN_(PointeeMatcher); +}; + +// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or +// reference that matches inner_matcher when dynamic_cast<T> is applied. +// The result of dynamic_cast<To> is forwarded to the inner matcher. +// If To is a pointer and the cast fails, the inner matcher will receive NULL. +// If To is a reference and the cast fails, this matcher returns false +// immediately. +template <typename To> +class WhenDynamicCastToMatcherBase { + public: + explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher) + : matcher_(matcher) {} + + void DescribeTo(::std::ostream* os) const { + GetCastTypeDescription(os); + matcher_.DescribeTo(os); + } + + void DescribeNegationTo(::std::ostream* os) const { + GetCastTypeDescription(os); + matcher_.DescribeNegationTo(os); + } + + protected: + const Matcher<To> matcher_; + + static string GetToName() { +#if GTEST_HAS_RTTI + return GetTypeName<To>(); +#else // GTEST_HAS_RTTI + return "the target type"; +#endif // GTEST_HAS_RTTI + } + + private: + static void GetCastTypeDescription(::std::ostream* os) { + *os << "when dynamic_cast to " << GetToName() << ", "; + } + + GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase); +}; + +// Primary template. +// To is a pointer. Cast and forward the result. +template <typename To> +class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> { + public: + explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher) + : WhenDynamicCastToMatcherBase<To>(matcher) {} + + template <typename From> + bool MatchAndExplain(From from, MatchResultListener* listener) const { + // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail? + To to = dynamic_cast<To>(from); + return MatchPrintAndExplain(to, this->matcher_, listener); + } +}; + +// Specialize for references. +// In this case we return false if the dynamic_cast fails. +template <typename To> +class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> { + public: + explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher) + : WhenDynamicCastToMatcherBase<To&>(matcher) {} + + template <typename From> + bool MatchAndExplain(From& from, MatchResultListener* listener) const { + // We don't want an std::bad_cast here, so do the cast with pointers. + To* to = dynamic_cast<To*>(&from); + if (to == NULL) { + *listener << "which cannot be dynamic_cast to " << this->GetToName(); + return false; + } + return MatchPrintAndExplain(*to, this->matcher_, listener); + } +}; + +// Implements the Field() matcher for matching a field (i.e. member +// variable) of an object. +template <typename Class, typename FieldType> +class FieldMatcher { + public: + FieldMatcher(FieldType Class::*field, + const Matcher<const FieldType&>& matcher) + : field_(field), matcher_(matcher) {} + + void DescribeTo(::std::ostream* os) const { + *os << "is an object whose given field "; + matcher_.DescribeTo(os); + } + + void DescribeNegationTo(::std::ostream* os) const { + *os << "is an object whose given field "; + matcher_.DescribeNegationTo(os); + } + + template <typename T> + bool MatchAndExplain(const T& value, MatchResultListener* listener) const { + return MatchAndExplainImpl( + typename ::testing::internal:: + is_pointer<GTEST_REMOVE_CONST_(T)>::type(), + value, listener); + } + + private: + // The first argument of MatchAndExplainImpl() is needed to help + // Symbian's C++ compiler choose which overload to use. Its type is + // true_type iff the Field() matcher is used to match a pointer. + bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, + MatchResultListener* listener) const { + *listener << "whose given field is "; + return MatchPrintAndExplain(obj.*field_, matcher_, listener); + } + + bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, + MatchResultListener* listener) const { + if (p == NULL) + return false; + + *listener << "which points to an object "; + // Since *p has a field, it must be a class/struct/union type and + // thus cannot be a pointer. Therefore we pass false_type() as + // the first argument. + return MatchAndExplainImpl(false_type(), *p, listener); + } + + const FieldType Class::*field_; + const Matcher<const FieldType&> matcher_; + + GTEST_DISALLOW_ASSIGN_(FieldMatcher); +}; + +// Implements the Property() matcher for matching a property +// (i.e. return value of a getter method) of an object. +template <typename Class, typename PropertyType> +class PropertyMatcher { + public: + // The property may have a reference type, so 'const PropertyType&' + // may cause double references and fail to compile. That's why we + // need GTEST_REFERENCE_TO_CONST, which works regardless of + // PropertyType being a reference or not. + typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty; + + PropertyMatcher(PropertyType (Class::*property)() const, + const Matcher<RefToConstProperty>& matcher) + : property_(property), matcher_(matcher) {} + + void DescribeTo(::std::ostream* os) const { + *os << "is an object whose given property "; + matcher_.DescribeTo(os); + } + + void DescribeNegationTo(::std::ostream* os) const { + *os << "is an object whose given property "; + matcher_.DescribeNegationTo(os); + } + + template <typename T> + bool MatchAndExplain(const T&value, MatchResultListener* listener) const { + return MatchAndExplainImpl( + typename ::testing::internal:: + is_pointer<GTEST_REMOVE_CONST_(T)>::type(), + value, listener); + } + + private: + // The first argument of MatchAndExplainImpl() is needed to help + // Symbian's C++ compiler choose which overload to use. Its type is + // true_type iff the Property() matcher is used to match a pointer. + bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, + MatchResultListener* listener) const { + *listener << "whose given property is "; + // Cannot pass the return value (for example, int) to MatchPrintAndExplain, + // which takes a non-const reference as argument. +#if defined(_PREFAST_ ) && _MSC_VER == 1800 + // Workaround bug in VC++ 2013's /analyze parser. + // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move + posix::Abort(); // To make sure it is never run. + return false; +#else + RefToConstProperty result = (obj.*property_)(); + return MatchPrintAndExplain(result, matcher_, listener); +#endif + } + + bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, + MatchResultListener* listener) const { + if (p == NULL) + return false; + + *listener << "which points to an object "; + // Since *p has a property method, it must be a class/struct/union + // type and thus cannot be a pointer. Therefore we pass + // false_type() as the first argument. + return MatchAndExplainImpl(false_type(), *p, listener); + } + + PropertyType (Class::*property_)() const; + const Matcher<RefToConstProperty> matcher_; + + GTEST_DISALLOW_ASSIGN_(PropertyMatcher); +}; + +// Type traits specifying various features of different functors for ResultOf. +// The default template specifies features for functor objects. +// Functor classes have to typedef argument_type and result_type +// to be compatible with ResultOf. +template <typename Functor> +struct CallableTraits { + typedef typename Functor::result_type ResultType; + typedef Functor StorageType; + + static void CheckIsValid(Functor /* functor */) {} + template <typename T> + static ResultType Invoke(Functor f, T arg) { return f(arg); } +}; + +// Specialization for function pointers. +template <typename ArgType, typename ResType> +struct CallableTraits<ResType(*)(ArgType)> { + typedef ResType ResultType; + typedef ResType(*StorageType)(ArgType); + + static void CheckIsValid(ResType(*f)(ArgType)) { + GTEST_CHECK_(f != NULL) + << "NULL function pointer is passed into ResultOf()."; + } + template <typename T> + static ResType Invoke(ResType(*f)(ArgType), T arg) { + return (*f)(arg); + } +}; + +// Implements the ResultOf() matcher for matching a return value of a +// unary function of an object. +template <typename Callable> +class ResultOfMatcher { + public: + typedef typename CallableTraits<Callable>::ResultType ResultType; + + ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher) + : callable_(callable), matcher_(matcher) { + CallableTraits<Callable>::CheckIsValid(callable_); + } + + template <typename T> + operator Matcher<T>() const { + return Matcher<T>(new Impl<T>(callable_, matcher_)); + } + + private: + typedef typename CallableTraits<Callable>::StorageType CallableStorageType; + + template <typename T> + class Impl : public MatcherInterface<T> { + public: + Impl(CallableStorageType callable, const Matcher<ResultType>& matcher) + : callable_(callable), matcher_(matcher) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "is mapped by the given callable to a value that "; + matcher_.DescribeTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "is mapped by the given callable to a value that "; + matcher_.DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const { + *listener << "which is mapped by the given callable to "; + // Cannot pass the return value (for example, int) to + // MatchPrintAndExplain, which takes a non-const reference as argument. + ResultType result = + CallableTraits<Callable>::template Invoke<T>(callable_, obj); + return MatchPrintAndExplain(result, matcher_, listener); + } + + private: + // Functors often define operator() as non-const method even though + // they are actualy stateless. But we need to use them even when + // 'this' is a const pointer. It's the user's responsibility not to + // use stateful callables with ResultOf(), which does't guarantee + // how many times the callable will be invoked. + mutable CallableStorageType callable_; + const Matcher<ResultType> matcher_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; // class Impl + + const CallableStorageType callable_; + const Matcher<ResultType> matcher_; + + GTEST_DISALLOW_ASSIGN_(ResultOfMatcher); +}; + +// Implements a matcher that checks the size of an STL-style container. +template <typename SizeMatcher> +class SizeIsMatcher { + public: + explicit SizeIsMatcher(const SizeMatcher& size_matcher) + : size_matcher_(size_matcher) { + } + + template <typename Container> + operator Matcher<Container>() const { + return MakeMatcher(new Impl<Container>(size_matcher_)); + } + + template <typename Container> + class Impl : public MatcherInterface<Container> { + public: + typedef internal::StlContainerView< + GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView; + typedef typename ContainerView::type::size_type SizeType; + explicit Impl(const SizeMatcher& size_matcher) + : size_matcher_(MatcherCast<SizeType>(size_matcher)) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "size "; + size_matcher_.DescribeTo(os); + } + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "size "; + size_matcher_.DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(Container container, + MatchResultListener* listener) const { + SizeType size = container.size(); + StringMatchResultListener size_listener; + const bool result = size_matcher_.MatchAndExplain(size, &size_listener); + *listener + << "whose size " << size << (result ? " matches" : " doesn't match"); + PrintIfNotEmpty(size_listener.str(), listener->stream()); + return result; + } + + private: + const Matcher<SizeType> size_matcher_; + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + private: + const SizeMatcher size_matcher_; + GTEST_DISALLOW_ASSIGN_(SizeIsMatcher); +}; + +// Implements a matcher that checks the begin()..end() distance of an STL-style +// container. +template <typename DistanceMatcher> +class BeginEndDistanceIsMatcher { + public: + explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher) + : distance_matcher_(distance_matcher) {} + + template <typename Container> + operator Matcher<Container>() const { + return MakeMatcher(new Impl<Container>(distance_matcher_)); + } + + template <typename Container> + class Impl : public MatcherInterface<Container> { + public: + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; + typedef internal::StlContainerView<RawContainer> View; + typedef typename View::type StlContainer; + typedef typename View::const_reference StlContainerReference; + typedef decltype(std::begin( + std::declval<StlContainerReference>())) StlContainerConstIterator; + typedef typename std::iterator_traits< + StlContainerConstIterator>::difference_type DistanceType; + explicit Impl(const DistanceMatcher& distance_matcher) + : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "distance between begin() and end() "; + distance_matcher_.DescribeTo(os); + } + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "distance between begin() and end() "; + distance_matcher_.DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(Container container, + MatchResultListener* listener) const { +#if GTEST_HAS_STD_BEGIN_AND_END_ + using std::begin; + using std::end; + DistanceType distance = std::distance(begin(container), end(container)); +#else + DistanceType distance = std::distance(container.begin(), container.end()); +#endif + StringMatchResultListener distance_listener; + const bool result = + distance_matcher_.MatchAndExplain(distance, &distance_listener); + *listener << "whose distance between begin() and end() " << distance + << (result ? " matches" : " doesn't match"); + PrintIfNotEmpty(distance_listener.str(), listener->stream()); + return result; + } + + private: + const Matcher<DistanceType> distance_matcher_; + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + private: + const DistanceMatcher distance_matcher_; + GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher); +}; + +// Implements an equality matcher for any STL-style container whose elements +// support ==. This matcher is like Eq(), but its failure explanations provide +// more detailed information that is useful when the container is used as a set. +// The failure message reports elements that are in one of the operands but not +// the other. The failure messages do not report duplicate or out-of-order +// elements in the containers (which don't properly matter to sets, but can +// occur if the containers are vectors or lists, for example). +// +// Uses the container's const_iterator, value_type, operator ==, +// begin(), and end(). +template <typename Container> +class ContainerEqMatcher { + public: + typedef internal::StlContainerView<Container> View; + typedef typename View::type StlContainer; + typedef typename View::const_reference StlContainerReference; + + // We make a copy of expected in case the elements in it are modified + // after this matcher is created. + explicit ContainerEqMatcher(const Container& expected) + : expected_(View::Copy(expected)) { + // Makes sure the user doesn't instantiate this class template + // with a const or reference type. + (void)testing::StaticAssertTypeEq<Container, + GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>(); + } + + void DescribeTo(::std::ostream* os) const { + *os << "equals "; + UniversalPrint(expected_, os); + } + void DescribeNegationTo(::std::ostream* os) const { + *os << "does not equal "; + UniversalPrint(expected_, os); + } + + template <typename LhsContainer> + bool MatchAndExplain(const LhsContainer& lhs, + MatchResultListener* listener) const { + // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug + // that causes LhsContainer to be a const type sometimes. + typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)> + LhsView; + typedef typename LhsView::type LhsStlContainer; + StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); + if (lhs_stl_container == expected_) + return true; + + ::std::ostream* const os = listener->stream(); + if (os != NULL) { + // Something is different. Check for extra values first. + bool printed_header = false; + for (typename LhsStlContainer::const_iterator it = + lhs_stl_container.begin(); + it != lhs_stl_container.end(); ++it) { + if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) == + expected_.end()) { + if (printed_header) { + *os << ", "; + } else { + *os << "which has these unexpected elements: "; + printed_header = true; + } + UniversalPrint(*it, os); + } + } + + // Now check for missing values. + bool printed_header2 = false; + for (typename StlContainer::const_iterator it = expected_.begin(); + it != expected_.end(); ++it) { + if (internal::ArrayAwareFind( + lhs_stl_container.begin(), lhs_stl_container.end(), *it) == + lhs_stl_container.end()) { + if (printed_header2) { + *os << ", "; + } else { + *os << (printed_header ? ",\nand" : "which") + << " doesn't have these expected elements: "; + printed_header2 = true; + } + UniversalPrint(*it, os); + } + } + } + + return false; + } + + private: + const StlContainer expected_; + + GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher); +}; + +// A comparator functor that uses the < operator to compare two values. +struct LessComparator { + template <typename T, typename U> + bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; } +}; + +// Implements WhenSortedBy(comparator, container_matcher). +template <typename Comparator, typename ContainerMatcher> +class WhenSortedByMatcher { + public: + WhenSortedByMatcher(const Comparator& comparator, + const ContainerMatcher& matcher) + : comparator_(comparator), matcher_(matcher) {} + + template <typename LhsContainer> + operator Matcher<LhsContainer>() const { + return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_)); + } + + template <typename LhsContainer> + class Impl : public MatcherInterface<LhsContainer> { + public: + typedef internal::StlContainerView< + GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; + typedef typename LhsView::type LhsStlContainer; + typedef typename LhsView::const_reference LhsStlContainerReference; + // Transforms std::pair<const Key, Value> into std::pair<Key, Value> + // so that we can match associative containers. + typedef typename RemoveConstFromKey< + typename LhsStlContainer::value_type>::type LhsValue; + + Impl(const Comparator& comparator, const ContainerMatcher& matcher) + : comparator_(comparator), matcher_(matcher) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "(when sorted) "; + matcher_.DescribeTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "(when sorted) "; + matcher_.DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(LhsContainer lhs, + MatchResultListener* listener) const { + LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); + ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(), + lhs_stl_container.end()); + ::std::sort( + sorted_container.begin(), sorted_container.end(), comparator_); + + if (!listener->IsInterested()) { + // If the listener is not interested, we do not need to + // construct the inner explanation. + return matcher_.Matches(sorted_container); + } + + *listener << "which is "; + UniversalPrint(sorted_container, listener->stream()); + *listener << " when sorted"; + + StringMatchResultListener inner_listener; + const bool match = matcher_.MatchAndExplain(sorted_container, + &inner_listener); + PrintIfNotEmpty(inner_listener.str(), listener->stream()); + return match; + } + + private: + const Comparator comparator_; + const Matcher<const ::std::vector<LhsValue>&> matcher_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); + }; + + private: + const Comparator comparator_; + const ContainerMatcher matcher_; + + GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher); +}; + +// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher +// must be able to be safely cast to Matcher<tuple<const T1&, const +// T2&> >, where T1 and T2 are the types of elements in the LHS +// container and the RHS container respectively. +template <typename TupleMatcher, typename RhsContainer> +class PointwiseMatcher { + public: + typedef internal::StlContainerView<RhsContainer> RhsView; + typedef typename RhsView::type RhsStlContainer; + typedef typename RhsStlContainer::value_type RhsValue; + + // Like ContainerEq, we make a copy of rhs in case the elements in + // it are modified after this matcher is created. + PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs) + : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) { + // Makes sure the user doesn't instantiate this class template + // with a const or reference type. + (void)testing::StaticAssertTypeEq<RhsContainer, + GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>(); + } + + template <typename LhsContainer> + operator Matcher<LhsContainer>() const { + return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_)); + } + + template <typename LhsContainer> + class Impl : public MatcherInterface<LhsContainer> { + public: + typedef internal::StlContainerView< + GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; + typedef typename LhsView::type LhsStlContainer; + typedef typename LhsView::const_reference LhsStlContainerReference; + typedef typename LhsStlContainer::value_type LhsValue; + // We pass the LHS value and the RHS value to the inner matcher by + // reference, as they may be expensive to copy. We must use tuple + // instead of pair here, as a pair cannot hold references (C++ 98, + // 20.2.2 [lib.pairs]). + typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg; + + Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs) + // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher. + : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)), + rhs_(rhs) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "contains " << rhs_.size() + << " values, where each value and its corresponding value in "; + UniversalPrinter<RhsStlContainer>::Print(rhs_, os); + *os << " "; + mono_tuple_matcher_.DescribeTo(os); + } + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "doesn't contain exactly " << rhs_.size() + << " values, or contains a value x at some index i" + << " where x and the i-th value of "; + UniversalPrint(rhs_, os); + *os << " "; + mono_tuple_matcher_.DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(LhsContainer lhs, + MatchResultListener* listener) const { + LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); + const size_t actual_size = lhs_stl_container.size(); + if (actual_size != rhs_.size()) { + *listener << "which contains " << actual_size << " values"; + return false; + } + + typename LhsStlContainer::const_iterator left = lhs_stl_container.begin(); + typename RhsStlContainer::const_iterator right = rhs_.begin(); + for (size_t i = 0; i != actual_size; ++i, ++left, ++right) { + const InnerMatcherArg value_pair(*left, *right); + + if (listener->IsInterested()) { + StringMatchResultListener inner_listener; + if (!mono_tuple_matcher_.MatchAndExplain( + value_pair, &inner_listener)) { + *listener << "where the value pair ("; + UniversalPrint(*left, listener->stream()); + *listener << ", "; + UniversalPrint(*right, listener->stream()); + *listener << ") at index #" << i << " don't match"; + PrintIfNotEmpty(inner_listener.str(), listener->stream()); + return false; + } + } else { + if (!mono_tuple_matcher_.Matches(value_pair)) + return false; + } + } + + return true; + } + + private: + const Matcher<InnerMatcherArg> mono_tuple_matcher_; + const RhsStlContainer rhs_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + private: + const TupleMatcher tuple_matcher_; + const RhsStlContainer rhs_; + + GTEST_DISALLOW_ASSIGN_(PointwiseMatcher); +}; + +// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl. +template <typename Container> +class QuantifierMatcherImpl : public MatcherInterface<Container> { + public: + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; + typedef StlContainerView<RawContainer> View; + typedef typename View::type StlContainer; + typedef typename View::const_reference StlContainerReference; + typedef typename StlContainer::value_type Element; + + template <typename InnerMatcher> + explicit QuantifierMatcherImpl(InnerMatcher inner_matcher) + : inner_matcher_( + testing::SafeMatcherCast<const Element&>(inner_matcher)) {} + + // Checks whether: + // * All elements in the container match, if all_elements_should_match. + // * Any element in the container matches, if !all_elements_should_match. + bool MatchAndExplainImpl(bool all_elements_should_match, + Container container, + MatchResultListener* listener) const { + StlContainerReference stl_container = View::ConstReference(container); + size_t i = 0; + for (typename StlContainer::const_iterator it = stl_container.begin(); + it != stl_container.end(); ++it, ++i) { + StringMatchResultListener inner_listener; + const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener); + + if (matches != all_elements_should_match) { + *listener << "whose element #" << i + << (matches ? " matches" : " doesn't match"); + PrintIfNotEmpty(inner_listener.str(), listener->stream()); + return !all_elements_should_match; + } + } + return all_elements_should_match; + } + + protected: + const Matcher<const Element&> inner_matcher_; + + GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl); +}; + +// Implements Contains(element_matcher) for the given argument type Container. +// Symmetric to EachMatcherImpl. +template <typename Container> +class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> { + public: + template <typename InnerMatcher> + explicit ContainsMatcherImpl(InnerMatcher inner_matcher) + : QuantifierMatcherImpl<Container>(inner_matcher) {} + + // Describes what this matcher does. + virtual void DescribeTo(::std::ostream* os) const { + *os << "contains at least one element that "; + this->inner_matcher_.DescribeTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "doesn't contain any element that "; + this->inner_matcher_.DescribeTo(os); + } + + virtual bool MatchAndExplain(Container container, + MatchResultListener* listener) const { + return this->MatchAndExplainImpl(false, container, listener); + } + + private: + GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl); +}; + +// Implements Each(element_matcher) for the given argument type Container. +// Symmetric to ContainsMatcherImpl. +template <typename Container> +class EachMatcherImpl : public QuantifierMatcherImpl<Container> { + public: + template <typename InnerMatcher> + explicit EachMatcherImpl(InnerMatcher inner_matcher) + : QuantifierMatcherImpl<Container>(inner_matcher) {} + + // Describes what this matcher does. + virtual void DescribeTo(::std::ostream* os) const { + *os << "only contains elements that "; + this->inner_matcher_.DescribeTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "contains some element that "; + this->inner_matcher_.DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(Container container, + MatchResultListener* listener) const { + return this->MatchAndExplainImpl(true, container, listener); + } + + private: + GTEST_DISALLOW_ASSIGN_(EachMatcherImpl); +}; + +// Implements polymorphic Contains(element_matcher). +template <typename M> +class ContainsMatcher { + public: + explicit ContainsMatcher(M m) : inner_matcher_(m) {} + + template <typename Container> + operator Matcher<Container>() const { + return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_)); + } + + private: + const M inner_matcher_; + + GTEST_DISALLOW_ASSIGN_(ContainsMatcher); +}; + +// Implements polymorphic Each(element_matcher). +template <typename M> +class EachMatcher { + public: + explicit EachMatcher(M m) : inner_matcher_(m) {} + + template <typename Container> + operator Matcher<Container>() const { + return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_)); + } + + private: + const M inner_matcher_; + + GTEST_DISALLOW_ASSIGN_(EachMatcher); +}; + +// Implements Key(inner_matcher) for the given argument pair type. +// Key(inner_matcher) matches an std::pair whose 'first' field matches +// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an +// std::map that contains at least one element whose key is >= 5. +template <typename PairType> +class KeyMatcherImpl : public MatcherInterface<PairType> { + public: + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; + typedef typename RawPairType::first_type KeyType; + + template <typename InnerMatcher> + explicit KeyMatcherImpl(InnerMatcher inner_matcher) + : inner_matcher_( + testing::SafeMatcherCast<const KeyType&>(inner_matcher)) { + } + + // Returns true iff 'key_value.first' (the key) matches the inner matcher. + virtual bool MatchAndExplain(PairType key_value, + MatchResultListener* listener) const { + StringMatchResultListener inner_listener; + const bool match = inner_matcher_.MatchAndExplain(key_value.first, + &inner_listener); + const internal::string explanation = inner_listener.str(); + if (explanation != "") { + *listener << "whose first field is a value " << explanation; + } + return match; + } + + // Describes what this matcher does. + virtual void DescribeTo(::std::ostream* os) const { + *os << "has a key that "; + inner_matcher_.DescribeTo(os); + } + + // Describes what the negation of this matcher does. + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "doesn't have a key that "; + inner_matcher_.DescribeTo(os); + } + + private: + const Matcher<const KeyType&> inner_matcher_; + + GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl); +}; + +// Implements polymorphic Key(matcher_for_key). +template <typename M> +class KeyMatcher { + public: + explicit KeyMatcher(M m) : matcher_for_key_(m) {} + + template <typename PairType> + operator Matcher<PairType>() const { + return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_)); + } + + private: + const M matcher_for_key_; + + GTEST_DISALLOW_ASSIGN_(KeyMatcher); +}; + +// Implements Pair(first_matcher, second_matcher) for the given argument pair +// type with its two matchers. See Pair() function below. +template <typename PairType> +class PairMatcherImpl : public MatcherInterface<PairType> { + public: + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; + typedef typename RawPairType::first_type FirstType; + typedef typename RawPairType::second_type SecondType; + + template <typename FirstMatcher, typename SecondMatcher> + PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher) + : first_matcher_( + testing::SafeMatcherCast<const FirstType&>(first_matcher)), + second_matcher_( + testing::SafeMatcherCast<const SecondType&>(second_matcher)) { + } + + // Describes what this matcher does. + virtual void DescribeTo(::std::ostream* os) const { + *os << "has a first field that "; + first_matcher_.DescribeTo(os); + *os << ", and has a second field that "; + second_matcher_.DescribeTo(os); + } + + // Describes what the negation of this matcher does. + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "has a first field that "; + first_matcher_.DescribeNegationTo(os); + *os << ", or has a second field that "; + second_matcher_.DescribeNegationTo(os); + } + + // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second' + // matches second_matcher. + virtual bool MatchAndExplain(PairType a_pair, + MatchResultListener* listener) const { + if (!listener->IsInterested()) { + // If the listener is not interested, we don't need to construct the + // explanation. + return first_matcher_.Matches(a_pair.first) && + second_matcher_.Matches(a_pair.second); + } + StringMatchResultListener first_inner_listener; + if (!first_matcher_.MatchAndExplain(a_pair.first, + &first_inner_listener)) { + *listener << "whose first field does not match"; + PrintIfNotEmpty(first_inner_listener.str(), listener->stream()); + return false; + } + StringMatchResultListener second_inner_listener; + if (!second_matcher_.MatchAndExplain(a_pair.second, + &second_inner_listener)) { + *listener << "whose second field does not match"; + PrintIfNotEmpty(second_inner_listener.str(), listener->stream()); + return false; + } + ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(), + listener); + return true; + } + + private: + void ExplainSuccess(const internal::string& first_explanation, + const internal::string& second_explanation, + MatchResultListener* listener) const { + *listener << "whose both fields match"; + if (first_explanation != "") { + *listener << ", where the first field is a value " << first_explanation; + } + if (second_explanation != "") { + *listener << ", "; + if (first_explanation != "") { + *listener << "and "; + } else { + *listener << "where "; + } + *listener << "the second field is a value " << second_explanation; + } + } + + const Matcher<const FirstType&> first_matcher_; + const Matcher<const SecondType&> second_matcher_; + + GTEST_DISALLOW_ASSIGN_(PairMatcherImpl); +}; + +// Implements polymorphic Pair(first_matcher, second_matcher). +template <typename FirstMatcher, typename SecondMatcher> +class PairMatcher { + public: + PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher) + : first_matcher_(first_matcher), second_matcher_(second_matcher) {} + + template <typename PairType> + operator Matcher<PairType> () const { + return MakeMatcher( + new PairMatcherImpl<PairType>( + first_matcher_, second_matcher_)); + } + + private: + const FirstMatcher first_matcher_; + const SecondMatcher second_matcher_; + + GTEST_DISALLOW_ASSIGN_(PairMatcher); +}; + +// Implements ElementsAre() and ElementsAreArray(). +template <typename Container> +class ElementsAreMatcherImpl : public MatcherInterface<Container> { + public: + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; + typedef internal::StlContainerView<RawContainer> View; + typedef typename View::type StlContainer; + typedef typename View::const_reference StlContainerReference; + typedef decltype(std::begin( + std::declval<StlContainerReference>())) StlContainerConstIterator; + typedef typename std::remove_reference<decltype( + *std::declval<StlContainerConstIterator &>())>::type Element; + + // Constructs the matcher from a sequence of element values or + // element matchers. + template <typename InputIter> + ElementsAreMatcherImpl(InputIter first, InputIter last) { + while (first != last) { + matchers_.push_back(MatcherCast<const Element&>(*first++)); + } + } + + // Describes what this matcher does. + virtual void DescribeTo(::std::ostream* os) const { + if (count() == 0) { + *os << "is empty"; + } else if (count() == 1) { + *os << "has 1 element that "; + matchers_[0].DescribeTo(os); + } else { + *os << "has " << Elements(count()) << " where\n"; + for (size_t i = 0; i != count(); ++i) { + *os << "element #" << i << " "; + matchers_[i].DescribeTo(os); + if (i + 1 < count()) { + *os << ",\n"; + } + } + } + } + + // Describes what the negation of this matcher does. + virtual void DescribeNegationTo(::std::ostream* os) const { + if (count() == 0) { + *os << "isn't empty"; + return; + } + + *os << "doesn't have " << Elements(count()) << ", or\n"; + for (size_t i = 0; i != count(); ++i) { + *os << "element #" << i << " "; + matchers_[i].DescribeNegationTo(os); + if (i + 1 < count()) { + *os << ", or\n"; + } + } + } + + virtual bool MatchAndExplain(Container container, + MatchResultListener* listener) const { + // To work with stream-like "containers", we must only walk + // through the elements in one pass. + + const bool listener_interested = listener->IsInterested(); + + // explanations[i] is the explanation of the element at index i. + ::std::vector<internal::string> explanations(count()); + StlContainerReference stl_container = View::ConstReference(container); + StlContainerConstIterator it = stl_container.begin(); + size_t exam_pos = 0; + bool mismatch_found = false; // Have we found a mismatched element yet? + + // Go through the elements and matchers in pairs, until we reach + // the end of either the elements or the matchers, or until we find a + // mismatch. + for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) { + bool match; // Does the current element match the current matcher? + if (listener_interested) { + StringMatchResultListener s; + match = matchers_[exam_pos].MatchAndExplain(*it, &s); + explanations[exam_pos] = s.str(); + } else { + match = matchers_[exam_pos].Matches(*it); + } + + if (!match) { + mismatch_found = true; + break; + } + } + // If mismatch_found is true, 'exam_pos' is the index of the mismatch. + + // Find how many elements the actual container has. We avoid + // calling size() s.t. this code works for stream-like "containers" + // that don't define size(). + size_t actual_count = exam_pos; + for (; it != stl_container.end(); ++it) { + ++actual_count; + } + + if (actual_count != count()) { + // The element count doesn't match. If the container is empty, + // there's no need to explain anything as Google Mock already + // prints the empty container. Otherwise we just need to show + // how many elements there actually are. + if (listener_interested && (actual_count != 0)) { + *listener << "which has " << Elements(actual_count); + } + return false; + } + + if (mismatch_found) { + // The element count matches, but the exam_pos-th element doesn't match. + if (listener_interested) { + *listener << "whose element #" << exam_pos << " doesn't match"; + PrintIfNotEmpty(explanations[exam_pos], listener->stream()); + } + return false; + } + + // Every element matches its expectation. We need to explain why + // (the obvious ones can be skipped). + if (listener_interested) { + bool reason_printed = false; + for (size_t i = 0; i != count(); ++i) { + const internal::string& s = explanations[i]; + if (!s.empty()) { + if (reason_printed) { + *listener << ",\nand "; + } + *listener << "whose element #" << i << " matches, " << s; + reason_printed = true; + } + } + } + return true; + } + + private: + static Message Elements(size_t count) { + return Message() << count << (count == 1 ? " element" : " elements"); + } + + size_t count() const { return matchers_.size(); } + + ::std::vector<Matcher<const Element&> > matchers_; + + GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl); +}; + +// Connectivity matrix of (elements X matchers), in element-major order. +// Initially, there are no edges. +// Use NextGraph() to iterate over all possible edge configurations. +// Use Randomize() to generate a random edge configuration. +class GTEST_API_ MatchMatrix { + public: + MatchMatrix(size_t num_elements, size_t num_matchers) + : num_elements_(num_elements), + num_matchers_(num_matchers), + matched_(num_elements_* num_matchers_, 0) { + } + + size_t LhsSize() const { return num_elements_; } + size_t RhsSize() const { return num_matchers_; } + bool HasEdge(size_t ilhs, size_t irhs) const { + return matched_[SpaceIndex(ilhs, irhs)] == 1; + } + void SetEdge(size_t ilhs, size_t irhs, bool b) { + matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0; + } + + // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number, + // adds 1 to that number; returns false if incrementing the graph left it + // empty. + bool NextGraph(); + + void Randomize(); + + string DebugString() const; + + private: + size_t SpaceIndex(size_t ilhs, size_t irhs) const { + return ilhs * num_matchers_ + irhs; + } + + size_t num_elements_; + size_t num_matchers_; + + // Each element is a char interpreted as bool. They are stored as a + // flattened array in lhs-major order, use 'SpaceIndex()' to translate + // a (ilhs, irhs) matrix coordinate into an offset. + ::std::vector<char> matched_; +}; + +typedef ::std::pair<size_t, size_t> ElementMatcherPair; +typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs; + +// Returns a maximum bipartite matching for the specified graph 'g'. +// The matching is represented as a vector of {element, matcher} pairs. +GTEST_API_ ElementMatcherPairs +FindMaxBipartiteMatching(const MatchMatrix& g); + +GTEST_API_ bool FindPairing(const MatchMatrix& matrix, + MatchResultListener* listener); + +// Untyped base class for implementing UnorderedElementsAre. By +// putting logic that's not specific to the element type here, we +// reduce binary bloat and increase compilation speed. +class GTEST_API_ UnorderedElementsAreMatcherImplBase { + protected: + // A vector of matcher describers, one for each element matcher. + // Does not own the describers (and thus can be used only when the + // element matchers are alive). + typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec; + + // Describes this UnorderedElementsAre matcher. + void DescribeToImpl(::std::ostream* os) const; + + // Describes the negation of this UnorderedElementsAre matcher. + void DescribeNegationToImpl(::std::ostream* os) const; + + bool VerifyAllElementsAndMatchersAreMatched( + const ::std::vector<string>& element_printouts, + const MatchMatrix& matrix, + MatchResultListener* listener) const; + + MatcherDescriberVec& matcher_describers() { + return matcher_describers_; + } + + static Message Elements(size_t n) { + return Message() << n << " element" << (n == 1 ? "" : "s"); + } + + private: + MatcherDescriberVec matcher_describers_; + + GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase); +}; + +// Implements unordered ElementsAre and unordered ElementsAreArray. +template <typename Container> +class UnorderedElementsAreMatcherImpl + : public MatcherInterface<Container>, + public UnorderedElementsAreMatcherImplBase { + public: + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; + typedef internal::StlContainerView<RawContainer> View; + typedef typename View::type StlContainer; + typedef typename View::const_reference StlContainerReference; + typedef decltype(std::begin( + std::declval<StlContainerReference>())) StlContainerConstIterator; + typedef typename std::remove_reference<decltype( + *std::declval<StlContainerConstIterator &>())>::type Element; + + // Constructs the matcher from a sequence of element values or + // element matchers. + template <typename InputIter> + UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) { + for (; first != last; ++first) { + matchers_.push_back(MatcherCast<const Element&>(*first)); + matcher_describers().push_back(matchers_.back().GetDescriber()); + } + } + + // Describes what this matcher does. + virtual void DescribeTo(::std::ostream* os) const { + return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os); + } + + // Describes what the negation of this matcher does. + virtual void DescribeNegationTo(::std::ostream* os) const { + return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os); + } + + virtual bool MatchAndExplain(Container container, + MatchResultListener* listener) const { + StlContainerReference stl_container = View::ConstReference(container); + ::std::vector<string> element_printouts; + MatchMatrix matrix = AnalyzeElements(stl_container.begin(), + stl_container.end(), + &element_printouts, + listener); + + const size_t actual_count = matrix.LhsSize(); + if (actual_count == 0 && matchers_.empty()) { + return true; + } + if (actual_count != matchers_.size()) { + // The element count doesn't match. If the container is empty, + // there's no need to explain anything as Google Mock already + // prints the empty container. Otherwise we just need to show + // how many elements there actually are. + if (actual_count != 0 && listener->IsInterested()) { + *listener << "which has " << Elements(actual_count); + } + return false; + } + + return VerifyAllElementsAndMatchersAreMatched(element_printouts, + matrix, listener) && + FindPairing(matrix, listener); + } + + private: + typedef ::std::vector<Matcher<const Element&> > MatcherVec; + + template <typename ElementIter> + MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last, + ::std::vector<string>* element_printouts, + MatchResultListener* listener) const { + element_printouts->clear(); + ::std::vector<char> did_match; + size_t num_elements = 0; + for (; elem_first != elem_last; ++num_elements, ++elem_first) { + if (listener->IsInterested()) { + element_printouts->push_back(PrintToString(*elem_first)); + } + for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { + did_match.push_back(Matches(matchers_[irhs])(*elem_first)); + } + } + + MatchMatrix matrix(num_elements, matchers_.size()); + ::std::vector<char>::const_iterator did_match_iter = did_match.begin(); + for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) { + for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { + matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0); + } + } + return matrix; + } + + MatcherVec matchers_; + + GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl); +}; + +// Functor for use in TransformTuple. +// Performs MatcherCast<Target> on an input argument of any type. +template <typename Target> +struct CastAndAppendTransform { + template <typename Arg> + Matcher<Target> operator()(const Arg& a) const { + return MatcherCast<Target>(a); + } +}; + +// Implements UnorderedElementsAre. +template <typename MatcherTuple> +class UnorderedElementsAreMatcher { + public: + explicit UnorderedElementsAreMatcher(const MatcherTuple& args) + : matchers_(args) {} + + template <typename Container> + operator Matcher<Container>() const { + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; + typedef internal::StlContainerView<RawContainer> View; + typedef typename View::const_reference StlContainerReference; + typedef decltype(std::begin( + std::declval<StlContainerReference>())) StlContainerConstIterator; + typedef typename std::remove_reference<decltype( + *std::declval<StlContainerConstIterator &>())>::type Element; + typedef ::std::vector<Matcher<const Element&> > MatcherVec; + MatcherVec matchers; + matchers.reserve(::testing::tuple_size<MatcherTuple>::value); + TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, + ::std::back_inserter(matchers)); + return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>( + matchers.begin(), matchers.end())); + } + + private: + const MatcherTuple matchers_; + GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher); +}; + +// Implements ElementsAre. +template <typename MatcherTuple> +class ElementsAreMatcher { + public: + explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {} + + template <typename Container> + operator Matcher<Container>() const { + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; + typedef internal::StlContainerView<RawContainer> View; + typedef typename View::const_reference StlContainerReference; + typedef decltype(std::begin( + std::declval<StlContainerReference>())) StlContainerConstIterator; + typedef typename std::remove_reference<decltype( + *std::declval<StlContainerConstIterator &>())>::type Element; + typedef ::std::vector<Matcher<const Element&> > MatcherVec; + MatcherVec matchers; + matchers.reserve(::testing::tuple_size<MatcherTuple>::value); + TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, + ::std::back_inserter(matchers)); + return MakeMatcher(new ElementsAreMatcherImpl<Container>( + matchers.begin(), matchers.end())); + } + + private: + const MatcherTuple matchers_; + GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher); +}; + +// Implements UnorderedElementsAreArray(). +template <typename T> +class UnorderedElementsAreArrayMatcher { + public: + UnorderedElementsAreArrayMatcher() {} + + template <typename Iter> + UnorderedElementsAreArrayMatcher(Iter first, Iter last) + : matchers_(first, last) {} + + template <typename Container> + operator Matcher<Container>() const { + return MakeMatcher( + new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(), + matchers_.end())); + } + + private: + ::std::vector<T> matchers_; + + GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher); +}; + +// Implements ElementsAreArray(). +template <typename T> +class ElementsAreArrayMatcher { + public: + template <typename Iter> + ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} + + template <typename Container> + operator Matcher<Container>() const { + return MakeMatcher(new ElementsAreMatcherImpl<Container>( + matchers_.begin(), matchers_.end())); + } + + private: + const ::std::vector<T> matchers_; + + GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher); +}; + +// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second +// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm, +// second) is a polymorphic matcher that matches a value x iff tm +// matches tuple (x, second). Useful for implementing +// UnorderedPointwise() in terms of UnorderedElementsAreArray(). +// +// BoundSecondMatcher is copyable and assignable, as we need to put +// instances of this class in a vector when implementing +// UnorderedPointwise(). +template <typename Tuple2Matcher, typename Second> +class BoundSecondMatcher { + public: + BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second) + : tuple2_matcher_(tm), second_value_(second) {} + + template <typename T> + operator Matcher<T>() const { + return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_)); + } + + // We have to define this for UnorderedPointwise() to compile in + // C++98 mode, as it puts BoundSecondMatcher instances in a vector, + // which requires the elements to be assignable in C++98. The + // compiler cannot generate the operator= for us, as Tuple2Matcher + // and Second may not be assignable. + // + // However, this should never be called, so the implementation just + // need to assert. + void operator=(const BoundSecondMatcher& /*rhs*/) { + GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned."; + } + + private: + template <typename T> + class Impl : public MatcherInterface<T> { + public: + typedef ::testing::tuple<T, Second> ArgTuple; + + Impl(const Tuple2Matcher& tm, const Second& second) + : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)), + second_value_(second) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "and "; + UniversalPrint(second_value_, os); + *os << " "; + mono_tuple2_matcher_.DescribeTo(os); + } + + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_), + listener); + } + + private: + const Matcher<const ArgTuple&> mono_tuple2_matcher_; + const Second second_value_; + + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + const Tuple2Matcher tuple2_matcher_; + const Second second_value_; +}; + +// Given a 2-tuple matcher tm and a value second, +// MatcherBindSecond(tm, second) returns a matcher that matches a +// value x iff tm matches tuple (x, second). Useful for implementing +// UnorderedPointwise() in terms of UnorderedElementsAreArray(). +template <typename Tuple2Matcher, typename Second> +BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond( + const Tuple2Matcher& tm, const Second& second) { + return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second); +} + +// Returns the description for a matcher defined using the MATCHER*() +// macro where the user-supplied description string is "", if +// 'negation' is false; otherwise returns the description of the +// negation of the matcher. 'param_values' contains a list of strings +// that are the print-out of the matcher's parameters. +GTEST_API_ string FormatMatcherDescription(bool negation, + const char* matcher_name, + const Strings& param_values); + +} // namespace internal + +// ElementsAreArray(first, last) +// ElementsAreArray(pointer, count) +// ElementsAreArray(array) +// ElementsAreArray(container) +// ElementsAreArray({ e1, e2, ..., en }) +// +// The ElementsAreArray() functions are like ElementsAre(...), except +// that they are given a homogeneous sequence rather than taking each +// element as a function argument. The sequence can be specified as an +// array, a pointer and count, a vector, an initializer list, or an +// STL iterator range. In each of these cases, the underlying sequence +// can be either a sequence of values or a sequence of matchers. +// +// All forms of ElementsAreArray() make a copy of the input matcher sequence. + +template <typename Iter> +inline internal::ElementsAreArrayMatcher< + typename ::std::iterator_traits<Iter>::value_type> +ElementsAreArray(Iter first, Iter last) { + typedef typename ::std::iterator_traits<Iter>::value_type T; + return internal::ElementsAreArrayMatcher<T>(first, last); +} + +template <typename T> +inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( + const T* pointer, size_t count) { + return ElementsAreArray(pointer, pointer + count); +} + +template <typename T, size_t N> +inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( + const T (&array)[N]) { + return ElementsAreArray(array, N); +} + +template <typename Container> +inline internal::ElementsAreArrayMatcher<typename Container::value_type> +ElementsAreArray(const Container& container) { + return ElementsAreArray(container.begin(), container.end()); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +template <typename T> +inline internal::ElementsAreArrayMatcher<T> +ElementsAreArray(::std::initializer_list<T> xs) { + return ElementsAreArray(xs.begin(), xs.end()); +} +#endif + +// UnorderedElementsAreArray(first, last) +// UnorderedElementsAreArray(pointer, count) +// UnorderedElementsAreArray(array) +// UnorderedElementsAreArray(container) +// UnorderedElementsAreArray({ e1, e2, ..., en }) +// +// The UnorderedElementsAreArray() functions are like +// ElementsAreArray(...), but allow matching the elements in any order. +template <typename Iter> +inline internal::UnorderedElementsAreArrayMatcher< + typename ::std::iterator_traits<Iter>::value_type> +UnorderedElementsAreArray(Iter first, Iter last) { + typedef typename ::std::iterator_traits<Iter>::value_type T; + return internal::UnorderedElementsAreArrayMatcher<T>(first, last); +} + +template <typename T> +inline internal::UnorderedElementsAreArrayMatcher<T> +UnorderedElementsAreArray(const T* pointer, size_t count) { + return UnorderedElementsAreArray(pointer, pointer + count); +} + +template <typename T, size_t N> +inline internal::UnorderedElementsAreArrayMatcher<T> +UnorderedElementsAreArray(const T (&array)[N]) { + return UnorderedElementsAreArray(array, N); +} + +template <typename Container> +inline internal::UnorderedElementsAreArrayMatcher< + typename Container::value_type> +UnorderedElementsAreArray(const Container& container) { + return UnorderedElementsAreArray(container.begin(), container.end()); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +template <typename T> +inline internal::UnorderedElementsAreArrayMatcher<T> +UnorderedElementsAreArray(::std::initializer_list<T> xs) { + return UnorderedElementsAreArray(xs.begin(), xs.end()); +} +#endif + +// _ is a matcher that matches anything of any type. +// +// This definition is fine as: +// +// 1. The C++ standard permits using the name _ in a namespace that +// is not the global namespace or ::std. +// 2. The AnythingMatcher class has no data member or constructor, +// so it's OK to create global variables of this type. +// 3. c-style has approved of using _ in this case. +const internal::AnythingMatcher _ = {}; +// Creates a matcher that matches any value of the given type T. +template <typename T> +inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); } + +// Creates a matcher that matches any value of the given type T. +template <typename T> +inline Matcher<T> An() { return A<T>(); } + +// Creates a polymorphic matcher that matches anything equal to x. +// Note: if the parameter of Eq() were declared as const T&, Eq("foo") +// wouldn't compile. +template <typename T> +inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); } + +// Constructs a Matcher<T> from a 'value' of type T. The constructed +// matcher matches any value that's equal to 'value'. +template <typename T> +Matcher<T>::Matcher(T value) { *this = Eq(value); } + +// Creates a monomorphic matcher that matches anything with type Lhs +// and equal to rhs. A user may need to use this instead of Eq(...) +// in order to resolve an overloading ambiguity. +// +// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x)) +// or Matcher<T>(x), but more readable than the latter. +// +// We could define similar monomorphic matchers for other comparison +// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do +// it yet as those are used much less than Eq() in practice. A user +// can always write Matcher<T>(Lt(5)) to be explicit about the type, +// for example. +template <typename Lhs, typename Rhs> +inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); } + +// Creates a polymorphic matcher that matches anything >= x. +template <typename Rhs> +inline internal::GeMatcher<Rhs> Ge(Rhs x) { + return internal::GeMatcher<Rhs>(x); +} + +// Creates a polymorphic matcher that matches anything > x. +template <typename Rhs> +inline internal::GtMatcher<Rhs> Gt(Rhs x) { + return internal::GtMatcher<Rhs>(x); +} + +// Creates a polymorphic matcher that matches anything <= x. +template <typename Rhs> +inline internal::LeMatcher<Rhs> Le(Rhs x) { + return internal::LeMatcher<Rhs>(x); +} + +// Creates a polymorphic matcher that matches anything < x. +template <typename Rhs> +inline internal::LtMatcher<Rhs> Lt(Rhs x) { + return internal::LtMatcher<Rhs>(x); +} + +// Creates a polymorphic matcher that matches anything != x. +template <typename Rhs> +inline internal::NeMatcher<Rhs> Ne(Rhs x) { + return internal::NeMatcher<Rhs>(x); +} + +// Creates a polymorphic matcher that matches any NULL pointer. +inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() { + return MakePolymorphicMatcher(internal::IsNullMatcher()); +} + +// Creates a polymorphic matcher that matches any non-NULL pointer. +// This is convenient as Not(NULL) doesn't compile (the compiler +// thinks that that expression is comparing a pointer with an integer). +inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() { + return MakePolymorphicMatcher(internal::NotNullMatcher()); +} + +// Creates a polymorphic matcher that matches any argument that +// references variable x. +template <typename T> +inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT + return internal::RefMatcher<T&>(x); +} + +// Creates a matcher that matches any double argument approximately +// equal to rhs, where two NANs are considered unequal. +inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) { + return internal::FloatingEqMatcher<double>(rhs, false); +} + +// Creates a matcher that matches any double argument approximately +// equal to rhs, including NaN values when rhs is NaN. +inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) { + return internal::FloatingEqMatcher<double>(rhs, true); +} + +// Creates a matcher that matches any double argument approximately equal to +// rhs, up to the specified max absolute error bound, where two NANs are +// considered unequal. The max absolute error bound must be non-negative. +inline internal::FloatingEqMatcher<double> DoubleNear( + double rhs, double max_abs_error) { + return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error); +} + +// Creates a matcher that matches any double argument approximately equal to +// rhs, up to the specified max absolute error bound, including NaN values when +// rhs is NaN. The max absolute error bound must be non-negative. +inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear( + double rhs, double max_abs_error) { + return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error); +} + +// Creates a matcher that matches any float argument approximately +// equal to rhs, where two NANs are considered unequal. +inline internal::FloatingEqMatcher<float> FloatEq(float rhs) { + return internal::FloatingEqMatcher<float>(rhs, false); +} + +// Creates a matcher that matches any float argument approximately +// equal to rhs, including NaN values when rhs is NaN. +inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) { + return internal::FloatingEqMatcher<float>(rhs, true); +} + +// Creates a matcher that matches any float argument approximately equal to +// rhs, up to the specified max absolute error bound, where two NANs are +// considered unequal. The max absolute error bound must be non-negative. +inline internal::FloatingEqMatcher<float> FloatNear( + float rhs, float max_abs_error) { + return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error); +} + +// Creates a matcher that matches any float argument approximately equal to +// rhs, up to the specified max absolute error bound, including NaN values when +// rhs is NaN. The max absolute error bound must be non-negative. +inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear( + float rhs, float max_abs_error) { + return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error); +} + +// Creates a matcher that matches a pointer (raw or smart) that points +// to a value that matches inner_matcher. +template <typename InnerMatcher> +inline internal::PointeeMatcher<InnerMatcher> Pointee( + const InnerMatcher& inner_matcher) { + return internal::PointeeMatcher<InnerMatcher>(inner_matcher); +} + +// Creates a matcher that matches a pointer or reference that matches +// inner_matcher when dynamic_cast<To> is applied. +// The result of dynamic_cast<To> is forwarded to the inner matcher. +// If To is a pointer and the cast fails, the inner matcher will receive NULL. +// If To is a reference and the cast fails, this matcher returns false +// immediately. +template <typename To> +inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> > +WhenDynamicCastTo(const Matcher<To>& inner_matcher) { + return MakePolymorphicMatcher( + internal::WhenDynamicCastToMatcher<To>(inner_matcher)); +} + +// Creates a matcher that matches an object whose given field matches +// 'matcher'. For example, +// Field(&Foo::number, Ge(5)) +// matches a Foo object x iff x.number >= 5. +template <typename Class, typename FieldType, typename FieldMatcher> +inline PolymorphicMatcher< + internal::FieldMatcher<Class, FieldType> > Field( + FieldType Class::*field, const FieldMatcher& matcher) { + return MakePolymorphicMatcher( + internal::FieldMatcher<Class, FieldType>( + field, MatcherCast<const FieldType&>(matcher))); + // The call to MatcherCast() is required for supporting inner + // matchers of compatible types. For example, it allows + // Field(&Foo::bar, m) + // to compile where bar is an int32 and m is a matcher for int64. +} + +// Creates a matcher that matches an object whose given property +// matches 'matcher'. For example, +// Property(&Foo::str, StartsWith("hi")) +// matches a Foo object x iff x.str() starts with "hi". +template <typename Class, typename PropertyType, typename PropertyMatcher> +inline PolymorphicMatcher< + internal::PropertyMatcher<Class, PropertyType> > Property( + PropertyType (Class::*property)() const, const PropertyMatcher& matcher) { + return MakePolymorphicMatcher( + internal::PropertyMatcher<Class, PropertyType>( + property, + MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher))); + // The call to MatcherCast() is required for supporting inner + // matchers of compatible types. For example, it allows + // Property(&Foo::bar, m) + // to compile where bar() returns an int32 and m is a matcher for int64. +} + +// Creates a matcher that matches an object iff the result of applying +// a callable to x matches 'matcher'. +// For example, +// ResultOf(f, StartsWith("hi")) +// matches a Foo object x iff f(x) starts with "hi". +// callable parameter can be a function, function pointer, or a functor. +// Callable has to satisfy the following conditions: +// * It is required to keep no state affecting the results of +// the calls on it and make no assumptions about how many calls +// will be made. Any state it keeps must be protected from the +// concurrent access. +// * If it is a function object, it has to define type result_type. +// We recommend deriving your functor classes from std::unary_function. +template <typename Callable, typename ResultOfMatcher> +internal::ResultOfMatcher<Callable> ResultOf( + Callable callable, const ResultOfMatcher& matcher) { + return internal::ResultOfMatcher<Callable>( + callable, + MatcherCast<typename internal::CallableTraits<Callable>::ResultType>( + matcher)); + // The call to MatcherCast() is required for supporting inner + // matchers of compatible types. For example, it allows + // ResultOf(Function, m) + // to compile where Function() returns an int32 and m is a matcher for int64. +} + +// String matchers. + +// Matches a string equal to str. +inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > + StrEq(const internal::string& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( + str, true, true)); +} + +// Matches a string not equal to str. +inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > + StrNe(const internal::string& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( + str, false, true)); +} + +// Matches a string equal to str, ignoring case. +inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > + StrCaseEq(const internal::string& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( + str, true, false)); +} + +// Matches a string not equal to str, ignoring case. +inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > + StrCaseNe(const internal::string& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( + str, false, false)); +} + +// Creates a matcher that matches any string, std::string, or C string +// that contains the given substring. +inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> > + HasSubstr(const internal::string& substring) { + return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>( + substring)); +} + +// Matches a string that starts with 'prefix' (case-sensitive). +inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> > + StartsWith(const internal::string& prefix) { + return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>( + prefix)); +} + +// Matches a string that ends with 'suffix' (case-sensitive). +inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> > + EndsWith(const internal::string& suffix) { + return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>( + suffix)); +} + +// Matches a string that fully matches regular expression 'regex'. +// The matcher takes ownership of 'regex'. +inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( + const internal::RE* regex) { + return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true)); +} +inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( + const internal::string& regex) { + return MatchesRegex(new internal::RE(regex)); +} + +// Matches a string that contains regular expression 'regex'. +// The matcher takes ownership of 'regex'. +inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( + const internal::RE* regex) { + return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false)); +} +inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( + const internal::string& regex) { + return ContainsRegex(new internal::RE(regex)); +} + +#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING +// Wide string matchers. + +// Matches a string equal to str. +inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > + StrEq(const internal::wstring& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( + str, true, true)); +} + +// Matches a string not equal to str. +inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > + StrNe(const internal::wstring& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( + str, false, true)); +} + +// Matches a string equal to str, ignoring case. +inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > + StrCaseEq(const internal::wstring& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( + str, true, false)); +} + +// Matches a string not equal to str, ignoring case. +inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > + StrCaseNe(const internal::wstring& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( + str, false, false)); +} + +// Creates a matcher that matches any wstring, std::wstring, or C wide string +// that contains the given substring. +inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> > + HasSubstr(const internal::wstring& substring) { + return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>( + substring)); +} + +// Matches a string that starts with 'prefix' (case-sensitive). +inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> > + StartsWith(const internal::wstring& prefix) { + return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>( + prefix)); +} + +// Matches a string that ends with 'suffix' (case-sensitive). +inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> > + EndsWith(const internal::wstring& suffix) { + return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>( + suffix)); +} + +#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING + +// Creates a polymorphic matcher that matches a 2-tuple where the +// first field == the second field. +inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); } + +// Creates a polymorphic matcher that matches a 2-tuple where the +// first field >= the second field. +inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); } + +// Creates a polymorphic matcher that matches a 2-tuple where the +// first field > the second field. +inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); } + +// Creates a polymorphic matcher that matches a 2-tuple where the +// first field <= the second field. +inline internal::Le2Matcher Le() { return internal::Le2Matcher(); } + +// Creates a polymorphic matcher that matches a 2-tuple where the +// first field < the second field. +inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); } + +// Creates a polymorphic matcher that matches a 2-tuple where the +// first field != the second field. +inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); } + +// Creates a matcher that matches any value of type T that m doesn't +// match. +template <typename InnerMatcher> +inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) { + return internal::NotMatcher<InnerMatcher>(m); +} + +// Returns a matcher that matches anything that satisfies the given +// predicate. The predicate can be any unary function or functor +// whose return type can be implicitly converted to bool. +template <typename Predicate> +inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> > +Truly(Predicate pred) { + return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred)); +} + +// Returns a matcher that matches the container size. The container must +// support both size() and size_type which all STL-like containers provide. +// Note that the parameter 'size' can be a value of type size_type as well as +// matcher. For instance: +// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements. +// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2. +template <typename SizeMatcher> +inline internal::SizeIsMatcher<SizeMatcher> +SizeIs(const SizeMatcher& size_matcher) { + return internal::SizeIsMatcher<SizeMatcher>(size_matcher); +} + +// Returns a matcher that matches the distance between the container's begin() +// iterator and its end() iterator, i.e. the size of the container. This matcher +// can be used instead of SizeIs with containers such as std::forward_list which +// do not implement size(). The container must provide const_iterator (with +// valid iterator_traits), begin() and end(). +template <typename DistanceMatcher> +inline internal::BeginEndDistanceIsMatcher<DistanceMatcher> +BeginEndDistanceIs(const DistanceMatcher& distance_matcher) { + return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher); +} + +// Returns a matcher that matches an equal container. +// This matcher behaves like Eq(), but in the event of mismatch lists the +// values that are included in one container but not the other. (Duplicate +// values and order differences are not explained.) +template <typename Container> +inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT + GTEST_REMOVE_CONST_(Container)> > + ContainerEq(const Container& rhs) { + // This following line is for working around a bug in MSVC 8.0, + // which causes Container to be a const type sometimes. + typedef GTEST_REMOVE_CONST_(Container) RawContainer; + return MakePolymorphicMatcher( + internal::ContainerEqMatcher<RawContainer>(rhs)); +} + +// Returns a matcher that matches a container that, when sorted using +// the given comparator, matches container_matcher. +template <typename Comparator, typename ContainerMatcher> +inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> +WhenSortedBy(const Comparator& comparator, + const ContainerMatcher& container_matcher) { + return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>( + comparator, container_matcher); +} + +// Returns a matcher that matches a container that, when sorted using +// the < operator, matches container_matcher. +template <typename ContainerMatcher> +inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher> +WhenSorted(const ContainerMatcher& container_matcher) { + return + internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>( + internal::LessComparator(), container_matcher); +} + +// Matches an STL-style container or a native array that contains the +// same number of elements as in rhs, where its i-th element and rhs's +// i-th element (as a pair) satisfy the given pair matcher, for all i. +// TupleMatcher must be able to be safely cast to Matcher<tuple<const +// T1&, const T2&> >, where T1 and T2 are the types of elements in the +// LHS container and the RHS container respectively. +template <typename TupleMatcher, typename Container> +inline internal::PointwiseMatcher<TupleMatcher, + GTEST_REMOVE_CONST_(Container)> +Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) { + // This following line is for working around a bug in MSVC 8.0, + // which causes Container to be a const type sometimes (e.g. when + // rhs is a const int[]).. + typedef GTEST_REMOVE_CONST_(Container) RawContainer; + return internal::PointwiseMatcher<TupleMatcher, RawContainer>( + tuple_matcher, rhs); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ + +// Supports the Pointwise(m, {a, b, c}) syntax. +template <typename TupleMatcher, typename T> +inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise( + const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) { + return Pointwise(tuple_matcher, std::vector<T>(rhs)); +} + +#endif // GTEST_HAS_STD_INITIALIZER_LIST_ + +// UnorderedPointwise(pair_matcher, rhs) matches an STL-style +// container or a native array that contains the same number of +// elements as in rhs, where in some permutation of the container, its +// i-th element and rhs's i-th element (as a pair) satisfy the given +// pair matcher, for all i. Tuple2Matcher must be able to be safely +// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are +// the types of elements in the LHS container and the RHS container +// respectively. +// +// This is like Pointwise(pair_matcher, rhs), except that the element +// order doesn't matter. +template <typename Tuple2Matcher, typename RhsContainer> +inline internal::UnorderedElementsAreArrayMatcher< + typename internal::BoundSecondMatcher< + Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_( + RhsContainer)>::type::value_type> > +UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, + const RhsContainer& rhs_container) { + // This following line is for working around a bug in MSVC 8.0, + // which causes RhsContainer to be a const type sometimes (e.g. when + // rhs_container is a const int[]). + typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer; + + // RhsView allows the same code to handle RhsContainer being a + // STL-style container and it being a native C-style array. + typedef typename internal::StlContainerView<RawRhsContainer> RhsView; + typedef typename RhsView::type RhsStlContainer; + typedef typename RhsStlContainer::value_type Second; + const RhsStlContainer& rhs_stl_container = + RhsView::ConstReference(rhs_container); + + // Create a matcher for each element in rhs_container. + ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers; + for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin(); + it != rhs_stl_container.end(); ++it) { + matchers.push_back( + internal::MatcherBindSecond(tuple2_matcher, *it)); + } + + // Delegate the work to UnorderedElementsAreArray(). + return UnorderedElementsAreArray(matchers); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ + +// Supports the UnorderedPointwise(m, {a, b, c}) syntax. +template <typename Tuple2Matcher, typename T> +inline internal::UnorderedElementsAreArrayMatcher< + typename internal::BoundSecondMatcher<Tuple2Matcher, T> > +UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, + std::initializer_list<T> rhs) { + return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs)); +} + +#endif // GTEST_HAS_STD_INITIALIZER_LIST_ + +// Matches an STL-style container or a native array that contains at +// least one element matching the given value or matcher. +// +// Examples: +// ::std::set<int> page_ids; +// page_ids.insert(3); +// page_ids.insert(1); +// EXPECT_THAT(page_ids, Contains(1)); +// EXPECT_THAT(page_ids, Contains(Gt(2))); +// EXPECT_THAT(page_ids, Not(Contains(4))); +// +// ::std::map<int, size_t> page_lengths; +// page_lengths[1] = 100; +// EXPECT_THAT(page_lengths, +// Contains(::std::pair<const int, size_t>(1, 100))); +// +// const char* user_ids[] = { "joe", "mike", "tom" }; +// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom")))); +template <typename M> +inline internal::ContainsMatcher<M> Contains(M matcher) { + return internal::ContainsMatcher<M>(matcher); +} + +// Matches an STL-style container or a native array that contains only +// elements matching the given value or matcher. +// +// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only +// the messages are different. +// +// Examples: +// ::std::set<int> page_ids; +// // Each(m) matches an empty container, regardless of what m is. +// EXPECT_THAT(page_ids, Each(Eq(1))); +// EXPECT_THAT(page_ids, Each(Eq(77))); +// +// page_ids.insert(3); +// EXPECT_THAT(page_ids, Each(Gt(0))); +// EXPECT_THAT(page_ids, Not(Each(Gt(4)))); +// page_ids.insert(1); +// EXPECT_THAT(page_ids, Not(Each(Lt(2)))); +// +// ::std::map<int, size_t> page_lengths; +// page_lengths[1] = 100; +// page_lengths[2] = 200; +// page_lengths[3] = 300; +// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100)))); +// EXPECT_THAT(page_lengths, Each(Key(Le(3)))); +// +// const char* user_ids[] = { "joe", "mike", "tom" }; +// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom"))))); +template <typename M> +inline internal::EachMatcher<M> Each(M matcher) { + return internal::EachMatcher<M>(matcher); +} + +// Key(inner_matcher) matches an std::pair whose 'first' field matches +// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an +// std::map that contains at least one element whose key is >= 5. +template <typename M> +inline internal::KeyMatcher<M> Key(M inner_matcher) { + return internal::KeyMatcher<M>(inner_matcher); +} + +// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field +// matches first_matcher and whose 'second' field matches second_matcher. For +// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used +// to match a std::map<int, string> that contains exactly one element whose key +// is >= 5 and whose value equals "foo". +template <typename FirstMatcher, typename SecondMatcher> +inline internal::PairMatcher<FirstMatcher, SecondMatcher> +Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) { + return internal::PairMatcher<FirstMatcher, SecondMatcher>( + first_matcher, second_matcher); +} + +// Returns a predicate that is satisfied by anything that matches the +// given matcher. +template <typename M> +inline internal::MatcherAsPredicate<M> Matches(M matcher) { + return internal::MatcherAsPredicate<M>(matcher); +} + +// Returns true iff the value matches the matcher. +template <typename T, typename M> +inline bool Value(const T& value, M matcher) { + return testing::Matches(matcher)(value); +} + +// Matches the value against the given matcher and explains the match +// result to listener. +template <typename T, typename M> +inline bool ExplainMatchResult( + M matcher, const T& value, MatchResultListener* listener) { + return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener); +} + +#if GTEST_LANG_CXX11 +// Define variadic matcher versions. They are overloaded in +// gmock-generated-matchers.h for the cases supported by pre C++11 compilers. +template <typename... Args> +inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) { + return internal::AllOfMatcher<Args...>(matchers...); +} + +template <typename... Args> +inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) { + return internal::AnyOfMatcher<Args...>(matchers...); +} + +#endif // GTEST_LANG_CXX11 + +// AllArgs(m) is a synonym of m. This is useful in +// +// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq())); +// +// which is easier to read than +// +// EXPECT_CALL(foo, Bar(_, _)).With(Eq()); +template <typename InnerMatcher> +inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; } + +// These macros allow using matchers to check values in Google Test +// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher) +// succeed iff the value matches the matcher. If the assertion fails, +// the value and the description of the matcher will be printed. +#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\ + ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) +#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\ + ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) + +} // namespace testing + +// Include any custom callback matchers added by the local installation. +// We must include this header at the end to make sure it can use the +// declarations from this file. +#include "gmock/internal/custom/gmock-matchers.h" +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-more-actions.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-more-actions.h new file mode 100644 index 00000000000..3d387b6b7d7 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-more-actions.h @@ -0,0 +1,246 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some actions that depend on gmock-generated-actions.h. + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ + +#include <algorithm> + +#include "gmock/gmock-generated-actions.h" + +namespace testing { +namespace internal { + +// Implements the Invoke(f) action. The template argument +// FunctionImpl is the implementation type of f, which can be either a +// function pointer or a functor. Invoke(f) can be used as an +// Action<F> as long as f's type is compatible with F (i.e. f can be +// assigned to a tr1::function<F>). +template <typename FunctionImpl> +class InvokeAction { + public: + // The c'tor makes a copy of function_impl (either a function + // pointer or a functor). + explicit InvokeAction(FunctionImpl function_impl) + : function_impl_(function_impl) {} + + template <typename Result, typename ArgumentTuple> + Result Perform(const ArgumentTuple& args) { + return InvokeHelper<Result, ArgumentTuple>::Invoke(function_impl_, args); + } + + private: + FunctionImpl function_impl_; + + GTEST_DISALLOW_ASSIGN_(InvokeAction); +}; + +// Implements the Invoke(object_ptr, &Class::Method) action. +template <class Class, typename MethodPtr> +class InvokeMethodAction { + public: + InvokeMethodAction(Class* obj_ptr, MethodPtr method_ptr) + : method_ptr_(method_ptr), obj_ptr_(obj_ptr) {} + + template <typename Result, typename ArgumentTuple> + Result Perform(const ArgumentTuple& args) const { + return InvokeHelper<Result, ArgumentTuple>::InvokeMethod( + obj_ptr_, method_ptr_, args); + } + + private: + // The order of these members matters. Reversing the order can trigger + // warning C4121 in MSVC (see + // http://computer-programming-forum.com/7-vc.net/6fbc30265f860ad1.htm ). + const MethodPtr method_ptr_; + Class* const obj_ptr_; + + GTEST_DISALLOW_ASSIGN_(InvokeMethodAction); +}; + +// An internal replacement for std::copy which mimics its behavior. This is +// necessary because Visual Studio deprecates ::std::copy, issuing warning 4996. +// However Visual Studio 2010 and later do not honor #pragmas which disable that +// warning. +template<typename InputIterator, typename OutputIterator> +inline OutputIterator CopyElements(InputIterator first, + InputIterator last, + OutputIterator output) { + for (; first != last; ++first, ++output) { + *output = *first; + } + return output; +} + +} // namespace internal + +// Various overloads for Invoke(). + +// Creates an action that invokes 'function_impl' with the mock +// function's arguments. +template <typename FunctionImpl> +PolymorphicAction<internal::InvokeAction<FunctionImpl> > Invoke( + FunctionImpl function_impl) { + return MakePolymorphicAction( + internal::InvokeAction<FunctionImpl>(function_impl)); +} + +// Creates an action that invokes the given method on the given object +// with the mock function's arguments. +template <class Class, typename MethodPtr> +PolymorphicAction<internal::InvokeMethodAction<Class, MethodPtr> > Invoke( + Class* obj_ptr, MethodPtr method_ptr) { + return MakePolymorphicAction( + internal::InvokeMethodAction<Class, MethodPtr>(obj_ptr, method_ptr)); +} + +// WithoutArgs(inner_action) can be used in a mock function with a +// non-empty argument list to perform inner_action, which takes no +// argument. In other words, it adapts an action accepting no +// argument to one that accepts (and ignores) arguments. +template <typename InnerAction> +inline internal::WithArgsAction<InnerAction> +WithoutArgs(const InnerAction& action) { + return internal::WithArgsAction<InnerAction>(action); +} + +// WithArg<k>(an_action) creates an action that passes the k-th +// (0-based) argument of the mock function to an_action and performs +// it. It adapts an action accepting one argument to one that accepts +// multiple arguments. For convenience, we also provide +// WithArgs<k>(an_action) (defined below) as a synonym. +template <int k, typename InnerAction> +inline internal::WithArgsAction<InnerAction, k> +WithArg(const InnerAction& action) { + return internal::WithArgsAction<InnerAction, k>(action); +} + +// The ACTION*() macros trigger warning C4100 (unreferenced formal +// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in +// the macro definition, as the warnings are generated when the macro +// is expanded and macro expansion cannot contain #pragma. Therefore +// we suppress them here. +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4100) +#endif + +// Action ReturnArg<k>() returns the k-th argument of the mock function. +ACTION_TEMPLATE(ReturnArg, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_0_VALUE_PARAMS()) { + return ::testing::get<k>(args); +} + +// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the +// mock function to *pointer. +ACTION_TEMPLATE(SaveArg, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_1_VALUE_PARAMS(pointer)) { + *pointer = ::testing::get<k>(args); +} + +// Action SaveArgPointee<k>(pointer) saves the value pointed to +// by the k-th (0-based) argument of the mock function to *pointer. +ACTION_TEMPLATE(SaveArgPointee, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_1_VALUE_PARAMS(pointer)) { + *pointer = *::testing::get<k>(args); +} + +// Action SetArgReferee<k>(value) assigns 'value' to the variable +// referenced by the k-th (0-based) argument of the mock function. +ACTION_TEMPLATE(SetArgReferee, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_1_VALUE_PARAMS(value)) { + typedef typename ::testing::tuple_element<k, args_type>::type argk_type; + // Ensures that argument #k is a reference. If you get a compiler + // error on the next line, you are using SetArgReferee<k>(value) in + // a mock function whose k-th (0-based) argument is not a reference. + GTEST_COMPILE_ASSERT_(internal::is_reference<argk_type>::value, + SetArgReferee_must_be_used_with_a_reference_argument); + ::testing::get<k>(args) = value; +} + +// Action SetArrayArgument<k>(first, last) copies the elements in +// source range [first, last) to the array pointed to by the k-th +// (0-based) argument, which can be either a pointer or an +// iterator. The action does not take ownership of the elements in the +// source range. +ACTION_TEMPLATE(SetArrayArgument, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_2_VALUE_PARAMS(first, last)) { + // Visual Studio deprecates ::std::copy, so we use our own copy in that case. +#ifdef _MSC_VER + internal::CopyElements(first, last, ::testing::get<k>(args)); +#else + ::std::copy(first, last, ::testing::get<k>(args)); +#endif +} + +// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock +// function. +ACTION_TEMPLATE(DeleteArg, + HAS_1_TEMPLATE_PARAMS(int, k), + AND_0_VALUE_PARAMS()) { + delete ::testing::get<k>(args); +} + +// This action returns the value pointed to by 'pointer'. +ACTION_P(ReturnPointee, pointer) { return *pointer; } + +// Action Throw(exception) can be used in a mock function of any type +// to throw the given exception. Any copyable value can be thrown. +#if GTEST_HAS_EXCEPTIONS + +// Suppresses the 'unreachable code' warning that VC generates in opt modes. +# ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4702) // Temporarily disables warning 4702. +# endif +ACTION_P(Throw, exception) { throw exception; } +# ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +# endif + +#endif // GTEST_HAS_EXCEPTIONS + +#ifdef _MSC_VER +# pragma warning(pop) +#endif + +} // namespace testing + +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-more-matchers.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-more-matchers.h new file mode 100644 index 00000000000..3db899f4297 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-more-matchers.h @@ -0,0 +1,58 @@ +// Copyright 2013, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: marcus.boerger@google.com (Marcus Boerger) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some matchers that depend on gmock-generated-matchers.h. +// +// Note that tests are implemented in gmock-matchers_test.cc rather than +// gmock-more-matchers-test.cc. + +#ifndef GMOCK_GMOCK_MORE_MATCHERS_H_ +#define GMOCK_GMOCK_MORE_MATCHERS_H_ + +#include "gmock/gmock-generated-matchers.h" + +namespace testing { + +// Defines a matcher that matches an empty container. The container must +// support both size() and empty(), which all STL-like containers provide. +MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") { + if (arg.empty()) { + return true; + } + *result_listener << "whose size is " << arg.size(); + return false; +} + +} // namespace testing + +#endif // GMOCK_GMOCK_MORE_MATCHERS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-spec-builders.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-spec-builders.h new file mode 100644 index 00000000000..fed7de66bc4 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock-spec-builders.h @@ -0,0 +1,1847 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements the ON_CALL() and EXPECT_CALL() macros. +// +// A user can use the ON_CALL() macro to specify the default action of +// a mock method. The syntax is: +// +// ON_CALL(mock_object, Method(argument-matchers)) +// .With(multi-argument-matcher) +// .WillByDefault(action); +// +// where the .With() clause is optional. +// +// A user can use the EXPECT_CALL() macro to specify an expectation on +// a mock method. The syntax is: +// +// EXPECT_CALL(mock_object, Method(argument-matchers)) +// .With(multi-argument-matchers) +// .Times(cardinality) +// .InSequence(sequences) +// .After(expectations) +// .WillOnce(action) +// .WillRepeatedly(action) +// .RetiresOnSaturation(); +// +// where all clauses are optional, and .InSequence()/.After()/ +// .WillOnce() can appear any number of times. + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ + +#include <map> +#include <set> +#include <sstream> +#include <string> +#include <vector> + +#if GTEST_HAS_EXCEPTIONS +# include <stdexcept> // NOLINT +#endif + +#include "gmock/gmock-actions.h" +#include "gmock/gmock-cardinalities.h" +#include "gmock/gmock-matchers.h" +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" + +namespace testing { + +// An abstract handle of an expectation. +class Expectation; + +// A set of expectation handles. +class ExpectationSet; + +// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION +// and MUST NOT BE USED IN USER CODE!!! +namespace internal { + +// Implements a mock function. +template <typename F> class FunctionMocker; + +// Base class for expectations. +class ExpectationBase; + +// Implements an expectation. +template <typename F> class TypedExpectation; + +// Helper class for testing the Expectation class template. +class ExpectationTester; + +// Base class for function mockers. +template <typename F> class FunctionMockerBase; + +// Protects the mock object registry (in class Mock), all function +// mockers, and all expectations. +// +// The reason we don't use more fine-grained protection is: when a +// mock function Foo() is called, it needs to consult its expectations +// to see which one should be picked. If another thread is allowed to +// call a mock function (either Foo() or a different one) at the same +// time, it could affect the "retired" attributes of Foo()'s +// expectations when InSequence() is used, and thus affect which +// expectation gets picked. Therefore, we sequence all mock function +// calls to ensure the integrity of the mock objects' states. +GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex); + +// Untyped base class for ActionResultHolder<R>. +class UntypedActionResultHolderBase; + +// Abstract base class of FunctionMockerBase. This is the +// type-agnostic part of the function mocker interface. Its pure +// virtual methods are implemented by FunctionMockerBase. +class GTEST_API_ UntypedFunctionMockerBase { + public: + UntypedFunctionMockerBase(); + virtual ~UntypedFunctionMockerBase(); + + // Verifies that all expectations on this mock function have been + // satisfied. Reports one or more Google Test non-fatal failures + // and returns false if not. + bool VerifyAndClearExpectationsLocked() + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + + // Clears the ON_CALL()s set on this mock function. + virtual void ClearDefaultActionsLocked() + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0; + + // In all of the following Untyped* functions, it's the caller's + // responsibility to guarantee the correctness of the arguments' + // types. + + // Performs the default action with the given arguments and returns + // the action's result. The call description string will be used in + // the error message to describe the call in the case the default + // action fails. + // L = * + virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( + const void* untyped_args, + const string& call_description) const = 0; + + // Performs the given action with the given arguments and returns + // the action's result. + // L = * + virtual UntypedActionResultHolderBase* UntypedPerformAction( + const void* untyped_action, + const void* untyped_args) const = 0; + + // Writes a message that the call is uninteresting (i.e. neither + // explicitly expected nor explicitly unexpected) to the given + // ostream. + virtual void UntypedDescribeUninterestingCall( + const void* untyped_args, + ::std::ostream* os) const + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; + + // Returns the expectation that matches the given function arguments + // (or NULL is there's no match); when a match is found, + // untyped_action is set to point to the action that should be + // performed (or NULL if the action is "do default"), and + // is_excessive is modified to indicate whether the call exceeds the + // expected number. + virtual const ExpectationBase* UntypedFindMatchingExpectation( + const void* untyped_args, + const void** untyped_action, bool* is_excessive, + ::std::ostream* what, ::std::ostream* why) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; + + // Prints the given function arguments to the ostream. + virtual void UntypedPrintArgs(const void* untyped_args, + ::std::ostream* os) const = 0; + + // Sets the mock object this mock method belongs to, and registers + // this information in the global mock registry. Will be called + // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock + // method. + // TODO(wan@google.com): rename to SetAndRegisterOwner(). + void RegisterOwner(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + + // Sets the mock object this mock method belongs to, and sets the + // name of the mock function. Will be called upon each invocation + // of this mock function. + void SetOwnerAndName(const void* mock_obj, const char* name) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + + // Returns the mock object this mock method belongs to. Must be + // called after RegisterOwner() or SetOwnerAndName() has been + // called. + const void* MockObject() const + GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + + // Returns the name of this mock method. Must be called after + // SetOwnerAndName() has been called. + const char* Name() const + GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + + // Returns the result of invoking this mock function with the given + // arguments. This function can be safely called from multiple + // threads concurrently. The caller is responsible for deleting the + // result. + UntypedActionResultHolderBase* UntypedInvokeWith( + const void* untyped_args) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + + protected: + typedef std::vector<const void*> UntypedOnCallSpecs; + + typedef std::vector<internal::linked_ptr<ExpectationBase> > + UntypedExpectations; + + // Returns an Expectation object that references and co-owns exp, + // which must be an expectation on this mock function. + Expectation GetHandleOf(ExpectationBase* exp); + + // Address of the mock object this mock method belongs to. Only + // valid after this mock method has been called or + // ON_CALL/EXPECT_CALL has been invoked on it. + const void* mock_obj_; // Protected by g_gmock_mutex. + + // Name of the function being mocked. Only valid after this mock + // method has been called. + const char* name_; // Protected by g_gmock_mutex. + + // All default action specs for this function mocker. + UntypedOnCallSpecs untyped_on_call_specs_; + + // All expectations for this function mocker. + UntypedExpectations untyped_expectations_; +}; // class UntypedFunctionMockerBase + +// Untyped base class for OnCallSpec<F>. +class UntypedOnCallSpecBase { + public: + // The arguments are the location of the ON_CALL() statement. + UntypedOnCallSpecBase(const char* a_file, int a_line) + : file_(a_file), line_(a_line), last_clause_(kNone) {} + + // Where in the source file was the default action spec defined? + const char* file() const { return file_; } + int line() const { return line_; } + + protected: + // Gives each clause in the ON_CALL() statement a name. + enum Clause { + // Do not change the order of the enum members! The run-time + // syntax checking relies on it. + kNone, + kWith, + kWillByDefault + }; + + // Asserts that the ON_CALL() statement has a certain property. + void AssertSpecProperty(bool property, const string& failure_message) const { + Assert(property, file_, line_, failure_message); + } + + // Expects that the ON_CALL() statement has a certain property. + void ExpectSpecProperty(bool property, const string& failure_message) const { + Expect(property, file_, line_, failure_message); + } + + const char* file_; + int line_; + + // The last clause in the ON_CALL() statement as seen so far. + // Initially kNone and changes as the statement is parsed. + Clause last_clause_; +}; // class UntypedOnCallSpecBase + +// This template class implements an ON_CALL spec. +template <typename F> +class OnCallSpec : public UntypedOnCallSpecBase { + public: + typedef typename Function<F>::ArgumentTuple ArgumentTuple; + typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; + + // Constructs an OnCallSpec object from the information inside + // the parenthesis of an ON_CALL() statement. + OnCallSpec(const char* a_file, int a_line, + const ArgumentMatcherTuple& matchers) + : UntypedOnCallSpecBase(a_file, a_line), + matchers_(matchers), + // By default, extra_matcher_ should match anything. However, + // we cannot initialize it with _ as that triggers a compiler + // bug in Symbian's C++ compiler (cannot decide between two + // overloaded constructors of Matcher<const ArgumentTuple&>). + extra_matcher_(A<const ArgumentTuple&>()) { + } + + // Implements the .With() clause. + OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) { + // Makes sure this is called at most once. + ExpectSpecProperty(last_clause_ < kWith, + ".With() cannot appear " + "more than once in an ON_CALL()."); + last_clause_ = kWith; + + extra_matcher_ = m; + return *this; + } + + // Implements the .WillByDefault() clause. + OnCallSpec& WillByDefault(const Action<F>& action) { + ExpectSpecProperty(last_clause_ < kWillByDefault, + ".WillByDefault() must appear " + "exactly once in an ON_CALL()."); + last_clause_ = kWillByDefault; + + ExpectSpecProperty(!action.IsDoDefault(), + "DoDefault() cannot be used in ON_CALL()."); + action_ = action; + return *this; + } + + // Returns true iff the given arguments match the matchers. + bool Matches(const ArgumentTuple& args) const { + return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); + } + + // Returns the action specified by the user. + const Action<F>& GetAction() const { + AssertSpecProperty(last_clause_ == kWillByDefault, + ".WillByDefault() must appear exactly " + "once in an ON_CALL()."); + return action_; + } + + private: + // The information in statement + // + // ON_CALL(mock_object, Method(matchers)) + // .With(multi-argument-matcher) + // .WillByDefault(action); + // + // is recorded in the data members like this: + // + // source file that contains the statement => file_ + // line number of the statement => line_ + // matchers => matchers_ + // multi-argument-matcher => extra_matcher_ + // action => action_ + ArgumentMatcherTuple matchers_; + Matcher<const ArgumentTuple&> extra_matcher_; + Action<F> action_; +}; // class OnCallSpec + +// Possible reactions on uninteresting calls. +enum CallReaction { + kAllow, + kWarn, + kFail, + kDefault = kWarn // By default, warn about uninteresting calls. +}; + +} // namespace internal + +// Utilities for manipulating mock objects. +class GTEST_API_ Mock { + public: + // The following public methods can be called concurrently. + + // Tells Google Mock to ignore mock_obj when checking for leaked + // mock objects. + static void AllowLeak(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + + // Verifies and clears all expectations on the given mock object. + // If the expectations aren't satisfied, generates one or more + // Google Test non-fatal failures and returns false. + static bool VerifyAndClearExpectations(void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + + // Verifies all expectations on the given mock object and clears its + // default actions and expectations. Returns true iff the + // verification was successful. + static bool VerifyAndClear(void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + + private: + friend class internal::UntypedFunctionMockerBase; + + // Needed for a function mocker to register itself (so that we know + // how to clear a mock object). + template <typename F> + friend class internal::FunctionMockerBase; + + template <typename M> + friend class NiceMock; + + template <typename M> + friend class NaggyMock; + + template <typename M> + friend class StrictMock; + + // Tells Google Mock to allow uninteresting calls on the given mock + // object. + static void AllowUninterestingCalls(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + + // Tells Google Mock to warn the user about uninteresting calls on + // the given mock object. + static void WarnUninterestingCalls(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + + // Tells Google Mock to fail uninteresting calls on the given mock + // object. + static void FailUninterestingCalls(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + + // Tells Google Mock the given mock object is being destroyed and + // its entry in the call-reaction table should be removed. + static void UnregisterCallReaction(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + + // Returns the reaction Google Mock will have on uninteresting calls + // made on the given mock object. + static internal::CallReaction GetReactionOnUninterestingCalls( + const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + + // Verifies that all expectations on the given mock object have been + // satisfied. Reports one or more Google Test non-fatal failures + // and returns false if not. + static bool VerifyAndClearExpectationsLocked(void* mock_obj) + GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); + + // Clears all ON_CALL()s set on the given mock object. + static void ClearDefaultActionsLocked(void* mock_obj) + GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); + + // Registers a mock object and a mock method it owns. + static void Register( + const void* mock_obj, + internal::UntypedFunctionMockerBase* mocker) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + + // Tells Google Mock where in the source code mock_obj is used in an + // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this + // information helps the user identify which object it is. + static void RegisterUseByOnCallOrExpectCall( + const void* mock_obj, const char* file, int line) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + + // Unregisters a mock method; removes the owning mock object from + // the registry when the last mock method associated with it has + // been unregistered. This is called only in the destructor of + // FunctionMockerBase. + static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) + GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); +}; // class Mock + +// An abstract handle of an expectation. Useful in the .After() +// clause of EXPECT_CALL() for setting the (partial) order of +// expectations. The syntax: +// +// Expectation e1 = EXPECT_CALL(...)...; +// EXPECT_CALL(...).After(e1)...; +// +// sets two expectations where the latter can only be matched after +// the former has been satisfied. +// +// Notes: +// - This class is copyable and has value semantics. +// - Constness is shallow: a const Expectation object itself cannot +// be modified, but the mutable methods of the ExpectationBase +// object it references can be called via expectation_base(). +// - The constructors and destructor are defined out-of-line because +// the Symbian WINSCW compiler wants to otherwise instantiate them +// when it sees this class definition, at which point it doesn't have +// ExpectationBase available yet, leading to incorrect destruction +// in the linked_ptr (or compilation errors if using a checking +// linked_ptr). +class GTEST_API_ Expectation { + public: + // Constructs a null object that doesn't reference any expectation. + Expectation(); + + ~Expectation(); + + // This single-argument ctor must not be explicit, in order to support the + // Expectation e = EXPECT_CALL(...); + // syntax. + // + // A TypedExpectation object stores its pre-requisites as + // Expectation objects, and needs to call the non-const Retire() + // method on the ExpectationBase objects they reference. Therefore + // Expectation must receive a *non-const* reference to the + // ExpectationBase object. + Expectation(internal::ExpectationBase& exp); // NOLINT + + // The compiler-generated copy ctor and operator= work exactly as + // intended, so we don't need to define our own. + + // Returns true iff rhs references the same expectation as this object does. + bool operator==(const Expectation& rhs) const { + return expectation_base_ == rhs.expectation_base_; + } + + bool operator!=(const Expectation& rhs) const { return !(*this == rhs); } + + private: + friend class ExpectationSet; + friend class Sequence; + friend class ::testing::internal::ExpectationBase; + friend class ::testing::internal::UntypedFunctionMockerBase; + + template <typename F> + friend class ::testing::internal::FunctionMockerBase; + + template <typename F> + friend class ::testing::internal::TypedExpectation; + + // This comparator is needed for putting Expectation objects into a set. + class Less { + public: + bool operator()(const Expectation& lhs, const Expectation& rhs) const { + return lhs.expectation_base_.get() < rhs.expectation_base_.get(); + } + }; + + typedef ::std::set<Expectation, Less> Set; + + Expectation( + const internal::linked_ptr<internal::ExpectationBase>& expectation_base); + + // Returns the expectation this object references. + const internal::linked_ptr<internal::ExpectationBase>& + expectation_base() const { + return expectation_base_; + } + + // A linked_ptr that co-owns the expectation this handle references. + internal::linked_ptr<internal::ExpectationBase> expectation_base_; +}; + +// A set of expectation handles. Useful in the .After() clause of +// EXPECT_CALL() for setting the (partial) order of expectations. The +// syntax: +// +// ExpectationSet es; +// es += EXPECT_CALL(...)...; +// es += EXPECT_CALL(...)...; +// EXPECT_CALL(...).After(es)...; +// +// sets three expectations where the last one can only be matched +// after the first two have both been satisfied. +// +// This class is copyable and has value semantics. +class ExpectationSet { + public: + // A bidirectional iterator that can read a const element in the set. + typedef Expectation::Set::const_iterator const_iterator; + + // An object stored in the set. This is an alias of Expectation. + typedef Expectation::Set::value_type value_type; + + // Constructs an empty set. + ExpectationSet() {} + + // This single-argument ctor must not be explicit, in order to support the + // ExpectationSet es = EXPECT_CALL(...); + // syntax. + ExpectationSet(internal::ExpectationBase& exp) { // NOLINT + *this += Expectation(exp); + } + + // This single-argument ctor implements implicit conversion from + // Expectation and thus must not be explicit. This allows either an + // Expectation or an ExpectationSet to be used in .After(). + ExpectationSet(const Expectation& e) { // NOLINT + *this += e; + } + + // The compiler-generator ctor and operator= works exactly as + // intended, so we don't need to define our own. + + // Returns true iff rhs contains the same set of Expectation objects + // as this does. + bool operator==(const ExpectationSet& rhs) const { + return expectations_ == rhs.expectations_; + } + + bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); } + + // Implements the syntax + // expectation_set += EXPECT_CALL(...); + ExpectationSet& operator+=(const Expectation& e) { + expectations_.insert(e); + return *this; + } + + int size() const { return static_cast<int>(expectations_.size()); } + + const_iterator begin() const { return expectations_.begin(); } + const_iterator end() const { return expectations_.end(); } + + private: + Expectation::Set expectations_; +}; + + +// Sequence objects are used by a user to specify the relative order +// in which the expectations should match. They are copyable (we rely +// on the compiler-defined copy constructor and assignment operator). +class GTEST_API_ Sequence { + public: + // Constructs an empty sequence. + Sequence() : last_expectation_(new Expectation) {} + + // Adds an expectation to this sequence. The caller must ensure + // that no other thread is accessing this Sequence object. + void AddExpectation(const Expectation& expectation) const; + + private: + // The last expectation in this sequence. We use a linked_ptr here + // because Sequence objects are copyable and we want the copies to + // be aliases. The linked_ptr allows the copies to co-own and share + // the same Expectation object. + internal::linked_ptr<Expectation> last_expectation_; +}; // class Sequence + +// An object of this type causes all EXPECT_CALL() statements +// encountered in its scope to be put in an anonymous sequence. The +// work is done in the constructor and destructor. You should only +// create an InSequence object on the stack. +// +// The sole purpose for this class is to support easy definition of +// sequential expectations, e.g. +// +// { +// InSequence dummy; // The name of the object doesn't matter. +// +// // The following expectations must match in the order they appear. +// EXPECT_CALL(a, Bar())...; +// EXPECT_CALL(a, Baz())...; +// ... +// EXPECT_CALL(b, Xyz())...; +// } +// +// You can create InSequence objects in multiple threads, as long as +// they are used to affect different mock objects. The idea is that +// each thread can create and set up its own mocks as if it's the only +// thread. However, for clarity of your tests we recommend you to set +// up mocks in the main thread unless you have a good reason not to do +// so. +class GTEST_API_ InSequence { + public: + InSequence(); + ~InSequence(); + private: + bool sequence_created_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT +} GTEST_ATTRIBUTE_UNUSED_; + +namespace internal { + +// Points to the implicit sequence introduced by a living InSequence +// object (if any) in the current thread or NULL. +GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence; + +// Base class for implementing expectations. +// +// There are two reasons for having a type-agnostic base class for +// Expectation: +// +// 1. We need to store collections of expectations of different +// types (e.g. all pre-requisites of a particular expectation, all +// expectations in a sequence). Therefore these expectation objects +// must share a common base class. +// +// 2. We can avoid binary code bloat by moving methods not depending +// on the template argument of Expectation to the base class. +// +// This class is internal and mustn't be used by user code directly. +class GTEST_API_ ExpectationBase { + public: + // source_text is the EXPECT_CALL(...) source that created this Expectation. + ExpectationBase(const char* file, int line, const string& source_text); + + virtual ~ExpectationBase(); + + // Where in the source file was the expectation spec defined? + const char* file() const { return file_; } + int line() const { return line_; } + const char* source_text() const { return source_text_.c_str(); } + // Returns the cardinality specified in the expectation spec. + const Cardinality& cardinality() const { return cardinality_; } + + // Describes the source file location of this expectation. + void DescribeLocationTo(::std::ostream* os) const { + *os << FormatFileLocation(file(), line()) << " "; + } + + // Describes how many times a function call matching this + // expectation has occurred. + void DescribeCallCountTo(::std::ostream* os) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + + // If this mock method has an extra matcher (i.e. .With(matcher)), + // describes it to the ostream. + virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0; + + protected: + friend class ::testing::Expectation; + friend class UntypedFunctionMockerBase; + + enum Clause { + // Don't change the order of the enum members! + kNone, + kWith, + kTimes, + kInSequence, + kAfter, + kWillOnce, + kWillRepeatedly, + kRetiresOnSaturation + }; + + typedef std::vector<const void*> UntypedActions; + + // Returns an Expectation object that references and co-owns this + // expectation. + virtual Expectation GetHandle() = 0; + + // Asserts that the EXPECT_CALL() statement has the given property. + void AssertSpecProperty(bool property, const string& failure_message) const { + Assert(property, file_, line_, failure_message); + } + + // Expects that the EXPECT_CALL() statement has the given property. + void ExpectSpecProperty(bool property, const string& failure_message) const { + Expect(property, file_, line_, failure_message); + } + + // Explicitly specifies the cardinality of this expectation. Used + // by the subclasses to implement the .Times() clause. + void SpecifyCardinality(const Cardinality& cardinality); + + // Returns true iff the user specified the cardinality explicitly + // using a .Times(). + bool cardinality_specified() const { return cardinality_specified_; } + + // Sets the cardinality of this expectation spec. + void set_cardinality(const Cardinality& a_cardinality) { + cardinality_ = a_cardinality; + } + + // The following group of methods should only be called after the + // EXPECT_CALL() statement, and only when g_gmock_mutex is held by + // the current thread. + + // Retires all pre-requisites of this expectation. + void RetireAllPreRequisites() + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + + // Returns true iff this expectation is retired. + bool is_retired() const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + return retired_; + } + + // Retires this expectation. + void Retire() + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + retired_ = true; + } + + // Returns true iff this expectation is satisfied. + bool IsSatisfied() const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + return cardinality().IsSatisfiedByCallCount(call_count_); + } + + // Returns true iff this expectation is saturated. + bool IsSaturated() const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + return cardinality().IsSaturatedByCallCount(call_count_); + } + + // Returns true iff this expectation is over-saturated. + bool IsOverSaturated() const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + return cardinality().IsOverSaturatedByCallCount(call_count_); + } + + // Returns true iff all pre-requisites of this expectation are satisfied. + bool AllPrerequisitesAreSatisfied() const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + + // Adds unsatisfied pre-requisites of this expectation to 'result'. + void FindUnsatisfiedPrerequisites(ExpectationSet* result) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + + // Returns the number this expectation has been invoked. + int call_count() const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + return call_count_; + } + + // Increments the number this expectation has been invoked. + void IncrementCallCount() + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + call_count_++; + } + + // Checks the action count (i.e. the number of WillOnce() and + // WillRepeatedly() clauses) against the cardinality if this hasn't + // been done before. Prints a warning if there are too many or too + // few actions. + void CheckActionCountIfNotDone() const + GTEST_LOCK_EXCLUDED_(mutex_); + + friend class ::testing::Sequence; + friend class ::testing::internal::ExpectationTester; + + template <typename Function> + friend class TypedExpectation; + + // Implements the .Times() clause. + void UntypedTimes(const Cardinality& a_cardinality); + + // This group of fields are part of the spec and won't change after + // an EXPECT_CALL() statement finishes. + const char* file_; // The file that contains the expectation. + int line_; // The line number of the expectation. + const string source_text_; // The EXPECT_CALL(...) source text. + // True iff the cardinality is specified explicitly. + bool cardinality_specified_; + Cardinality cardinality_; // The cardinality of the expectation. + // The immediate pre-requisites (i.e. expectations that must be + // satisfied before this expectation can be matched) of this + // expectation. We use linked_ptr in the set because we want an + // Expectation object to be co-owned by its FunctionMocker and its + // successors. This allows multiple mock objects to be deleted at + // different times. + ExpectationSet immediate_prerequisites_; + + // This group of fields are the current state of the expectation, + // and can change as the mock function is called. + int call_count_; // How many times this expectation has been invoked. + bool retired_; // True iff this expectation has retired. + UntypedActions untyped_actions_; + bool extra_matcher_specified_; + bool repeated_action_specified_; // True if a WillRepeatedly() was specified. + bool retires_on_saturation_; + Clause last_clause_; + mutable bool action_count_checked_; // Under mutex_. + mutable Mutex mutex_; // Protects action_count_checked_. + + GTEST_DISALLOW_ASSIGN_(ExpectationBase); +}; // class ExpectationBase + +// Impements an expectation for the given function type. +template <typename F> +class TypedExpectation : public ExpectationBase { + public: + typedef typename Function<F>::ArgumentTuple ArgumentTuple; + typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; + typedef typename Function<F>::Result Result; + + TypedExpectation(FunctionMockerBase<F>* owner, + const char* a_file, int a_line, const string& a_source_text, + const ArgumentMatcherTuple& m) + : ExpectationBase(a_file, a_line, a_source_text), + owner_(owner), + matchers_(m), + // By default, extra_matcher_ should match anything. However, + // we cannot initialize it with _ as that triggers a compiler + // bug in Symbian's C++ compiler (cannot decide between two + // overloaded constructors of Matcher<const ArgumentTuple&>). + extra_matcher_(A<const ArgumentTuple&>()), + repeated_action_(DoDefault()) {} + + virtual ~TypedExpectation() { + // Check the validity of the action count if it hasn't been done + // yet (for example, if the expectation was never used). + CheckActionCountIfNotDone(); + for (UntypedActions::const_iterator it = untyped_actions_.begin(); + it != untyped_actions_.end(); ++it) { + delete static_cast<const Action<F>*>(*it); + } + } + + // Implements the .With() clause. + TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) { + if (last_clause_ == kWith) { + ExpectSpecProperty(false, + ".With() cannot appear " + "more than once in an EXPECT_CALL()."); + } else { + ExpectSpecProperty(last_clause_ < kWith, + ".With() must be the first " + "clause in an EXPECT_CALL()."); + } + last_clause_ = kWith; + + extra_matcher_ = m; + extra_matcher_specified_ = true; + return *this; + } + + // Implements the .Times() clause. + TypedExpectation& Times(const Cardinality& a_cardinality) { + ExpectationBase::UntypedTimes(a_cardinality); + return *this; + } + + // Implements the .Times() clause. + TypedExpectation& Times(int n) { + return Times(Exactly(n)); + } + + // Implements the .InSequence() clause. + TypedExpectation& InSequence(const Sequence& s) { + ExpectSpecProperty(last_clause_ <= kInSequence, + ".InSequence() cannot appear after .After()," + " .WillOnce(), .WillRepeatedly(), or " + ".RetiresOnSaturation()."); + last_clause_ = kInSequence; + + s.AddExpectation(GetHandle()); + return *this; + } + TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) { + return InSequence(s1).InSequence(s2); + } + TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, + const Sequence& s3) { + return InSequence(s1, s2).InSequence(s3); + } + TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, + const Sequence& s3, const Sequence& s4) { + return InSequence(s1, s2, s3).InSequence(s4); + } + TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, + const Sequence& s3, const Sequence& s4, + const Sequence& s5) { + return InSequence(s1, s2, s3, s4).InSequence(s5); + } + + // Implements that .After() clause. + TypedExpectation& After(const ExpectationSet& s) { + ExpectSpecProperty(last_clause_ <= kAfter, + ".After() cannot appear after .WillOnce()," + " .WillRepeatedly(), or " + ".RetiresOnSaturation()."); + last_clause_ = kAfter; + + for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) { + immediate_prerequisites_ += *it; + } + return *this; + } + TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) { + return After(s1).After(s2); + } + TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, + const ExpectationSet& s3) { + return After(s1, s2).After(s3); + } + TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, + const ExpectationSet& s3, const ExpectationSet& s4) { + return After(s1, s2, s3).After(s4); + } + TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, + const ExpectationSet& s3, const ExpectationSet& s4, + const ExpectationSet& s5) { + return After(s1, s2, s3, s4).After(s5); + } + + // Implements the .WillOnce() clause. + TypedExpectation& WillOnce(const Action<F>& action) { + ExpectSpecProperty(last_clause_ <= kWillOnce, + ".WillOnce() cannot appear after " + ".WillRepeatedly() or .RetiresOnSaturation()."); + last_clause_ = kWillOnce; + + untyped_actions_.push_back(new Action<F>(action)); + if (!cardinality_specified()) { + set_cardinality(Exactly(static_cast<int>(untyped_actions_.size()))); + } + return *this; + } + + // Implements the .WillRepeatedly() clause. + TypedExpectation& WillRepeatedly(const Action<F>& action) { + if (last_clause_ == kWillRepeatedly) { + ExpectSpecProperty(false, + ".WillRepeatedly() cannot appear " + "more than once in an EXPECT_CALL()."); + } else { + ExpectSpecProperty(last_clause_ < kWillRepeatedly, + ".WillRepeatedly() cannot appear " + "after .RetiresOnSaturation()."); + } + last_clause_ = kWillRepeatedly; + repeated_action_specified_ = true; + + repeated_action_ = action; + if (!cardinality_specified()) { + set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size()))); + } + + // Now that no more action clauses can be specified, we check + // whether their count makes sense. + CheckActionCountIfNotDone(); + return *this; + } + + // Implements the .RetiresOnSaturation() clause. + TypedExpectation& RetiresOnSaturation() { + ExpectSpecProperty(last_clause_ < kRetiresOnSaturation, + ".RetiresOnSaturation() cannot appear " + "more than once."); + last_clause_ = kRetiresOnSaturation; + retires_on_saturation_ = true; + + // Now that no more action clauses can be specified, we check + // whether their count makes sense. + CheckActionCountIfNotDone(); + return *this; + } + + // Returns the matchers for the arguments as specified inside the + // EXPECT_CALL() macro. + const ArgumentMatcherTuple& matchers() const { + return matchers_; + } + + // Returns the matcher specified by the .With() clause. + const Matcher<const ArgumentTuple&>& extra_matcher() const { + return extra_matcher_; + } + + // Returns the action specified by the .WillRepeatedly() clause. + const Action<F>& repeated_action() const { return repeated_action_; } + + // If this mock method has an extra matcher (i.e. .With(matcher)), + // describes it to the ostream. + virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) { + if (extra_matcher_specified_) { + *os << " Expected args: "; + extra_matcher_.DescribeTo(os); + *os << "\n"; + } + } + + private: + template <typename Function> + friend class FunctionMockerBase; + + // Returns an Expectation object that references and co-owns this + // expectation. + virtual Expectation GetHandle() { + return owner_->GetHandleOf(this); + } + + // The following methods will be called only after the EXPECT_CALL() + // statement finishes and when the current thread holds + // g_gmock_mutex. + + // Returns true iff this expectation matches the given arguments. + bool Matches(const ArgumentTuple& args) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); + } + + // Returns true iff this expectation should handle the given arguments. + bool ShouldHandleArguments(const ArgumentTuple& args) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + + // In case the action count wasn't checked when the expectation + // was defined (e.g. if this expectation has no WillRepeatedly() + // or RetiresOnSaturation() clause), we check it when the + // expectation is used for the first time. + CheckActionCountIfNotDone(); + return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args); + } + + // Describes the result of matching the arguments against this + // expectation to the given ostream. + void ExplainMatchResultTo( + const ArgumentTuple& args, + ::std::ostream* os) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + + if (is_retired()) { + *os << " Expected: the expectation is active\n" + << " Actual: it is retired\n"; + } else if (!Matches(args)) { + if (!TupleMatches(matchers_, args)) { + ExplainMatchFailureTupleTo(matchers_, args, os); + } + StringMatchResultListener listener; + if (!extra_matcher_.MatchAndExplain(args, &listener)) { + *os << " Expected args: "; + extra_matcher_.DescribeTo(os); + *os << "\n Actual: don't match"; + + internal::PrintIfNotEmpty(listener.str(), os); + *os << "\n"; + } + } else if (!AllPrerequisitesAreSatisfied()) { + *os << " Expected: all pre-requisites are satisfied\n" + << " Actual: the following immediate pre-requisites " + << "are not satisfied:\n"; + ExpectationSet unsatisfied_prereqs; + FindUnsatisfiedPrerequisites(&unsatisfied_prereqs); + int i = 0; + for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin(); + it != unsatisfied_prereqs.end(); ++it) { + it->expectation_base()->DescribeLocationTo(os); + *os << "pre-requisite #" << i++ << "\n"; + } + *os << " (end of pre-requisites)\n"; + } else { + // This line is here just for completeness' sake. It will never + // be executed as currently the ExplainMatchResultTo() function + // is called only when the mock function call does NOT match the + // expectation. + *os << "The call matches the expectation.\n"; + } + } + + // Returns the action that should be taken for the current invocation. + const Action<F>& GetCurrentAction( + const FunctionMockerBase<F>* mocker, + const ArgumentTuple& args) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + const int count = call_count(); + Assert(count >= 1, __FILE__, __LINE__, + "call_count() is <= 0 when GetCurrentAction() is " + "called - this should never happen."); + + const int action_count = static_cast<int>(untyped_actions_.size()); + if (action_count > 0 && !repeated_action_specified_ && + count > action_count) { + // If there is at least one WillOnce() and no WillRepeatedly(), + // we warn the user when the WillOnce() clauses ran out. + ::std::stringstream ss; + DescribeLocationTo(&ss); + ss << "Actions ran out in " << source_text() << "...\n" + << "Called " << count << " times, but only " + << action_count << " WillOnce()" + << (action_count == 1 ? " is" : "s are") << " specified - "; + mocker->DescribeDefaultActionTo(args, &ss); + Log(kWarning, ss.str(), 1); + } + + return count <= action_count ? + *static_cast<const Action<F>*>(untyped_actions_[count - 1]) : + repeated_action(); + } + + // Given the arguments of a mock function call, if the call will + // over-saturate this expectation, returns the default action; + // otherwise, returns the next action in this expectation. Also + // describes *what* happened to 'what', and explains *why* Google + // Mock does it to 'why'. This method is not const as it calls + // IncrementCallCount(). A return value of NULL means the default + // action. + const Action<F>* GetActionForArguments( + const FunctionMockerBase<F>* mocker, + const ArgumentTuple& args, + ::std::ostream* what, + ::std::ostream* why) + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + if (IsSaturated()) { + // We have an excessive call. + IncrementCallCount(); + *what << "Mock function called more times than expected - "; + mocker->DescribeDefaultActionTo(args, what); + DescribeCallCountTo(why); + + // TODO(wan@google.com): allow the user to control whether + // unexpected calls should fail immediately or continue using a + // flag --gmock_unexpected_calls_are_fatal. + return NULL; + } + + IncrementCallCount(); + RetireAllPreRequisites(); + + if (retires_on_saturation_ && IsSaturated()) { + Retire(); + } + + // Must be done after IncrementCount()! + *what << "Mock function call matches " << source_text() <<"...\n"; + return &(GetCurrentAction(mocker, args)); + } + + // All the fields below won't change once the EXPECT_CALL() + // statement finishes. + FunctionMockerBase<F>* const owner_; + ArgumentMatcherTuple matchers_; + Matcher<const ArgumentTuple&> extra_matcher_; + Action<F> repeated_action_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation); +}; // class TypedExpectation + +// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for +// specifying the default behavior of, or expectation on, a mock +// function. + +// Note: class MockSpec really belongs to the ::testing namespace. +// However if we define it in ::testing, MSVC will complain when +// classes in ::testing::internal declare it as a friend class +// template. To workaround this compiler bug, we define MockSpec in +// ::testing::internal and import it into ::testing. + +// Logs a message including file and line number information. +GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, + const char* file, int line, + const string& message); + +template <typename F> +class MockSpec { + public: + typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; + typedef typename internal::Function<F>::ArgumentMatcherTuple + ArgumentMatcherTuple; + + // Constructs a MockSpec object, given the function mocker object + // that the spec is associated with. + explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker) + : function_mocker_(function_mocker) {} + + // Adds a new default action spec to the function mocker and returns + // the newly created spec. + internal::OnCallSpec<F>& InternalDefaultActionSetAt( + const char* file, int line, const char* obj, const char* call) { + LogWithLocation(internal::kInfo, file, line, + string("ON_CALL(") + obj + ", " + call + ") invoked"); + return function_mocker_->AddNewOnCallSpec(file, line, matchers_); + } + + // Adds a new expectation spec to the function mocker and returns + // the newly created spec. + internal::TypedExpectation<F>& InternalExpectedAt( + const char* file, int line, const char* obj, const char* call) { + const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")"); + LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); + return function_mocker_->AddNewExpectation( + file, line, source_text, matchers_); + } + + private: + template <typename Function> + friend class internal::FunctionMocker; + + void SetMatchers(const ArgumentMatcherTuple& matchers) { + matchers_ = matchers; + } + + // The function mocker that owns this spec. + internal::FunctionMockerBase<F>* const function_mocker_; + // The argument matchers specified in the spec. + ArgumentMatcherTuple matchers_; + + GTEST_DISALLOW_ASSIGN_(MockSpec); +}; // class MockSpec + +// Wrapper type for generically holding an ordinary value or lvalue reference. +// If T is not a reference type, it must be copyable or movable. +// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless +// T is a move-only value type (which means that it will always be copyable +// if the current platform does not support move semantics). +// +// The primary template defines handling for values, but function header +// comments describe the contract for the whole template (including +// specializations). +template <typename T> +class ReferenceOrValueWrapper { + public: + // Constructs a wrapper from the given value/reference. + explicit ReferenceOrValueWrapper(T value) + : value_(::testing::internal::move(value)) { + } + + // Unwraps and returns the underlying value/reference, exactly as + // originally passed. The behavior of calling this more than once on + // the same object is unspecified. + T Unwrap() { return ::testing::internal::move(value_); } + + // Provides nondestructive access to the underlying value/reference. + // Always returns a const reference (more precisely, + // const RemoveReference<T>&). The behavior of calling this after + // calling Unwrap on the same object is unspecified. + const T& Peek() const { + return value_; + } + + private: + T value_; +}; + +// Specialization for lvalue reference types. See primary template +// for documentation. +template <typename T> +class ReferenceOrValueWrapper<T&> { + public: + // Workaround for debatable pass-by-reference lint warning (c-library-team + // policy precludes NOLINT in this context) + typedef T& reference; + explicit ReferenceOrValueWrapper(reference ref) + : value_ptr_(&ref) {} + T& Unwrap() { return *value_ptr_; } + const T& Peek() const { return *value_ptr_; } + + private: + T* value_ptr_; +}; + +// MSVC warns about using 'this' in base member initializer list, so +// we need to temporarily disable the warning. We have to do it for +// the entire class to suppress the warning, even though it's about +// the constructor only. + +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4355) // Temporarily disables warning 4355. +#endif // _MSV_VER + +// C++ treats the void type specially. For example, you cannot define +// a void-typed variable or pass a void value to a function. +// ActionResultHolder<T> holds a value of type T, where T must be a +// copyable type or void (T doesn't need to be default-constructable). +// It hides the syntactic difference between void and other types, and +// is used to unify the code for invoking both void-returning and +// non-void-returning mock functions. + +// Untyped base class for ActionResultHolder<T>. +class UntypedActionResultHolderBase { + public: + virtual ~UntypedActionResultHolderBase() {} + + // Prints the held value as an action's result to os. + virtual void PrintAsActionResult(::std::ostream* os) const = 0; +}; + +// This generic definition is used when T is not void. +template <typename T> +class ActionResultHolder : public UntypedActionResultHolderBase { + public: + // Returns the held value. Must not be called more than once. + T Unwrap() { + return result_.Unwrap(); + } + + // Prints the held value as an action's result to os. + virtual void PrintAsActionResult(::std::ostream* os) const { + *os << "\n Returns: "; + // T may be a reference type, so we don't use UniversalPrint(). + UniversalPrinter<T>::Print(result_.Peek(), os); + } + + // Performs the given mock function's default action and returns the + // result in a new-ed ActionResultHolder. + template <typename F> + static ActionResultHolder* PerformDefaultAction( + const FunctionMockerBase<F>* func_mocker, + const typename Function<F>::ArgumentTuple& args, + const string& call_description) { + return new ActionResultHolder(Wrapper( + func_mocker->PerformDefaultAction(args, call_description))); + } + + // Performs the given action and returns the result in a new-ed + // ActionResultHolder. + template <typename F> + static ActionResultHolder* + PerformAction(const Action<F>& action, + const typename Function<F>::ArgumentTuple& args) { + return new ActionResultHolder(Wrapper(action.Perform(args))); + } + + private: + typedef ReferenceOrValueWrapper<T> Wrapper; + + explicit ActionResultHolder(Wrapper result) + : result_(::testing::internal::move(result)) { + } + + Wrapper result_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); +}; + +// Specialization for T = void. +template <> +class ActionResultHolder<void> : public UntypedActionResultHolderBase { + public: + void Unwrap() { } + + virtual void PrintAsActionResult(::std::ostream* /* os */) const {} + + // Performs the given mock function's default action and returns ownership + // of an empty ActionResultHolder*. + template <typename F> + static ActionResultHolder* PerformDefaultAction( + const FunctionMockerBase<F>* func_mocker, + const typename Function<F>::ArgumentTuple& args, + const string& call_description) { + func_mocker->PerformDefaultAction(args, call_description); + return new ActionResultHolder; + } + + // Performs the given action and returns ownership of an empty + // ActionResultHolder*. + template <typename F> + static ActionResultHolder* PerformAction( + const Action<F>& action, + const typename Function<F>::ArgumentTuple& args) { + action.Perform(args); + return new ActionResultHolder; + } + + private: + ActionResultHolder() {} + GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); +}; + +// The base of the function mocker class for the given function type. +// We put the methods in this class instead of its child to avoid code +// bloat. +template <typename F> +class FunctionMockerBase : public UntypedFunctionMockerBase { + public: + typedef typename Function<F>::Result Result; + typedef typename Function<F>::ArgumentTuple ArgumentTuple; + typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; + + FunctionMockerBase() : current_spec_(this) {} + + // The destructor verifies that all expectations on this mock + // function have been satisfied. If not, it will report Google Test + // non-fatal failures for the violations. + virtual ~FunctionMockerBase() + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + MutexLock l(&g_gmock_mutex); + VerifyAndClearExpectationsLocked(); + Mock::UnregisterLocked(this); + ClearDefaultActionsLocked(); + } + + // Returns the ON_CALL spec that matches this mock function with the + // given arguments; returns NULL if no matching ON_CALL is found. + // L = * + const OnCallSpec<F>* FindOnCallSpec( + const ArgumentTuple& args) const { + for (UntypedOnCallSpecs::const_reverse_iterator it + = untyped_on_call_specs_.rbegin(); + it != untyped_on_call_specs_.rend(); ++it) { + const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it); + if (spec->Matches(args)) + return spec; + } + + return NULL; + } + + // Performs the default action of this mock function on the given + // arguments and returns the result. Asserts (or throws if + // exceptions are enabled) with a helpful call descrption if there + // is no valid return value. This method doesn't depend on the + // mutable state of this object, and thus can be called concurrently + // without locking. + // L = * + Result PerformDefaultAction(const ArgumentTuple& args, + const string& call_description) const { + const OnCallSpec<F>* const spec = + this->FindOnCallSpec(args); + if (spec != NULL) { + return spec->GetAction().Perform(args); + } + const string message = call_description + + "\n The mock function has no default action " + "set, and its return type has no default value set."; +#if GTEST_HAS_EXCEPTIONS + if (!DefaultValue<Result>::Exists()) { + throw std::runtime_error(message); + } +#else + Assert(DefaultValue<Result>::Exists(), "", -1, message); +#endif + return DefaultValue<Result>::Get(); + } + + // Performs the default action with the given arguments and returns + // the action's result. The call description string will be used in + // the error message to describe the call in the case the default + // action fails. The caller is responsible for deleting the result. + // L = * + virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( + const void* untyped_args, // must point to an ArgumentTuple + const string& call_description) const { + const ArgumentTuple& args = + *static_cast<const ArgumentTuple*>(untyped_args); + return ResultHolder::PerformDefaultAction(this, args, call_description); + } + + // Performs the given action with the given arguments and returns + // the action's result. The caller is responsible for deleting the + // result. + // L = * + virtual UntypedActionResultHolderBase* UntypedPerformAction( + const void* untyped_action, const void* untyped_args) const { + // Make a copy of the action before performing it, in case the + // action deletes the mock object (and thus deletes itself). + const Action<F> action = *static_cast<const Action<F>*>(untyped_action); + const ArgumentTuple& args = + *static_cast<const ArgumentTuple*>(untyped_args); + return ResultHolder::PerformAction(action, args); + } + + // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked(): + // clears the ON_CALL()s set on this mock function. + virtual void ClearDefaultActionsLocked() + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + + // Deleting our default actions may trigger other mock objects to be + // deleted, for example if an action contains a reference counted smart + // pointer to that mock object, and that is the last reference. So if we + // delete our actions within the context of the global mutex we may deadlock + // when this method is called again. Instead, make a copy of the set of + // actions to delete, clear our set within the mutex, and then delete the + // actions outside of the mutex. + UntypedOnCallSpecs specs_to_delete; + untyped_on_call_specs_.swap(specs_to_delete); + + g_gmock_mutex.Unlock(); + for (UntypedOnCallSpecs::const_iterator it = + specs_to_delete.begin(); + it != specs_to_delete.end(); ++it) { + delete static_cast<const OnCallSpec<F>*>(*it); + } + + // Lock the mutex again, since the caller expects it to be locked when we + // return. + g_gmock_mutex.Lock(); + } + + protected: + template <typename Function> + friend class MockSpec; + + typedef ActionResultHolder<Result> ResultHolder; + + // Returns the result of invoking this mock function with the given + // arguments. This function can be safely called from multiple + // threads concurrently. + Result InvokeWith(const ArgumentTuple& args) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + scoped_ptr<ResultHolder> holder( + DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args))); + return holder->Unwrap(); + } + + // Adds and returns a default action spec for this mock function. + OnCallSpec<F>& AddNewOnCallSpec( + const char* file, int line, + const ArgumentMatcherTuple& m) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); + OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m); + untyped_on_call_specs_.push_back(on_call_spec); + return *on_call_spec; + } + + // Adds and returns an expectation spec for this mock function. + TypedExpectation<F>& AddNewExpectation( + const char* file, + int line, + const string& source_text, + const ArgumentMatcherTuple& m) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); + TypedExpectation<F>* const expectation = + new TypedExpectation<F>(this, file, line, source_text, m); + const linked_ptr<ExpectationBase> untyped_expectation(expectation); + untyped_expectations_.push_back(untyped_expectation); + + // Adds this expectation into the implicit sequence if there is one. + Sequence* const implicit_sequence = g_gmock_implicit_sequence.get(); + if (implicit_sequence != NULL) { + implicit_sequence->AddExpectation(Expectation(untyped_expectation)); + } + + return *expectation; + } + + // The current spec (either default action spec or expectation spec) + // being described on this function mocker. + MockSpec<F>& current_spec() { return current_spec_; } + + private: + template <typename Func> friend class TypedExpectation; + + // Some utilities needed for implementing UntypedInvokeWith(). + + // Describes what default action will be performed for the given + // arguments. + // L = * + void DescribeDefaultActionTo(const ArgumentTuple& args, + ::std::ostream* os) const { + const OnCallSpec<F>* const spec = FindOnCallSpec(args); + + if (spec == NULL) { + *os << (internal::type_equals<Result, void>::value ? + "returning directly.\n" : + "returning default value.\n"); + } else { + *os << "taking default action specified at:\n" + << FormatFileLocation(spec->file(), spec->line()) << "\n"; + } + } + + // Writes a message that the call is uninteresting (i.e. neither + // explicitly expected nor explicitly unexpected) to the given + // ostream. + virtual void UntypedDescribeUninterestingCall( + const void* untyped_args, + ::std::ostream* os) const + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + const ArgumentTuple& args = + *static_cast<const ArgumentTuple*>(untyped_args); + *os << "Uninteresting mock function call - "; + DescribeDefaultActionTo(args, os); + *os << " Function call: " << Name(); + UniversalPrint(args, os); + } + + // Returns the expectation that matches the given function arguments + // (or NULL is there's no match); when a match is found, + // untyped_action is set to point to the action that should be + // performed (or NULL if the action is "do default"), and + // is_excessive is modified to indicate whether the call exceeds the + // expected number. + // + // Critical section: We must find the matching expectation and the + // corresponding action that needs to be taken in an ATOMIC + // transaction. Otherwise another thread may call this mock + // method in the middle and mess up the state. + // + // However, performing the action has to be left out of the critical + // section. The reason is that we have no control on what the + // action does (it can invoke an arbitrary user function or even a + // mock function) and excessive locking could cause a dead lock. + virtual const ExpectationBase* UntypedFindMatchingExpectation( + const void* untyped_args, + const void** untyped_action, bool* is_excessive, + ::std::ostream* what, ::std::ostream* why) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + const ArgumentTuple& args = + *static_cast<const ArgumentTuple*>(untyped_args); + MutexLock l(&g_gmock_mutex); + TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args); + if (exp == NULL) { // A match wasn't found. + this->FormatUnexpectedCallMessageLocked(args, what, why); + return NULL; + } + + // This line must be done before calling GetActionForArguments(), + // which will increment the call count for *exp and thus affect + // its saturation status. + *is_excessive = exp->IsSaturated(); + const Action<F>* action = exp->GetActionForArguments(this, args, what, why); + if (action != NULL && action->IsDoDefault()) + action = NULL; // Normalize "do default" to NULL. + *untyped_action = action; + return exp; + } + + // Prints the given function arguments to the ostream. + virtual void UntypedPrintArgs(const void* untyped_args, + ::std::ostream* os) const { + const ArgumentTuple& args = + *static_cast<const ArgumentTuple*>(untyped_args); + UniversalPrint(args, os); + } + + // Returns the expectation that matches the arguments, or NULL if no + // expectation matches them. + TypedExpectation<F>* FindMatchingExpectationLocked( + const ArgumentTuple& args) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + for (typename UntypedExpectations::const_reverse_iterator it = + untyped_expectations_.rbegin(); + it != untyped_expectations_.rend(); ++it) { + TypedExpectation<F>* const exp = + static_cast<TypedExpectation<F>*>(it->get()); + if (exp->ShouldHandleArguments(args)) { + return exp; + } + } + return NULL; + } + + // Returns a message that the arguments don't match any expectation. + void FormatUnexpectedCallMessageLocked( + const ArgumentTuple& args, + ::std::ostream* os, + ::std::ostream* why) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + *os << "\nUnexpected mock function call - "; + DescribeDefaultActionTo(args, os); + PrintTriedExpectationsLocked(args, why); + } + + // Prints a list of expectations that have been tried against the + // current mock function call. + void PrintTriedExpectationsLocked( + const ArgumentTuple& args, + ::std::ostream* why) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + const int count = static_cast<int>(untyped_expectations_.size()); + *why << "Google Mock tried the following " << count << " " + << (count == 1 ? "expectation, but it didn't match" : + "expectations, but none matched") + << ":\n"; + for (int i = 0; i < count; i++) { + TypedExpectation<F>* const expectation = + static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get()); + *why << "\n"; + expectation->DescribeLocationTo(why); + if (count > 1) { + *why << "tried expectation #" << i << ": "; + } + *why << expectation->source_text() << "...\n"; + expectation->ExplainMatchResultTo(args, why); + expectation->DescribeCallCountTo(why); + } + } + + // The current spec (either default action spec or expectation spec) + // being described on this function mocker. + MockSpec<F> current_spec_; + + // There is no generally useful and implementable semantics of + // copying a mock object, so copying a mock is usually a user error. + // Thus we disallow copying function mockers. If the user really + // wants to copy a mock object, he should implement his own copy + // operation, for example: + // + // class MockFoo : public Foo { + // public: + // // Defines a copy constructor explicitly. + // MockFoo(const MockFoo& src) {} + // ... + // }; + GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase); +}; // class FunctionMockerBase + +#ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +#endif // _MSV_VER + +// Implements methods of FunctionMockerBase. + +// Verifies that all expectations on this mock function have been +// satisfied. Reports one or more Google Test non-fatal failures and +// returns false if not. + +// Reports an uninteresting call (whose description is in msg) in the +// manner specified by 'reaction'. +void ReportUninterestingCall(CallReaction reaction, const string& msg); + +} // namespace internal + +// The style guide prohibits "using" statements in a namespace scope +// inside a header file. However, the MockSpec class template is +// meant to be defined in the ::testing namespace. The following line +// is just a trick for working around a bug in MSVC 8.0, which cannot +// handle it if we define MockSpec in ::testing. +using internal::MockSpec; + +// Const(x) is a convenient function for obtaining a const reference +// to x. This is useful for setting expectations on an overloaded +// const mock method, e.g. +// +// class MockFoo : public FooInterface { +// public: +// MOCK_METHOD0(Bar, int()); +// MOCK_CONST_METHOD0(Bar, int&()); +// }; +// +// MockFoo foo; +// // Expects a call to non-const MockFoo::Bar(). +// EXPECT_CALL(foo, Bar()); +// // Expects a call to const MockFoo::Bar(). +// EXPECT_CALL(Const(foo), Bar()); +template <typename T> +inline const T& Const(const T& x) { return x; } + +// Constructs an Expectation object that references and co-owns exp. +inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT + : expectation_base_(exp.GetHandle().expectation_base()) {} + +} // namespace testing + +// A separate macro is required to avoid compile errors when the name +// of the method used in call is a result of macro expansion. +// See CompilesWithMethodNameExpandedFromMacro tests in +// internal/gmock-spec-builders_test.cc for more details. +#define GMOCK_ON_CALL_IMPL_(obj, call) \ + ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \ + #obj, #call) +#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call) + +#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \ + ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call) +#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call) + +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock.h new file mode 100644 index 00000000000..6735c71bf8a --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/gmock.h @@ -0,0 +1,94 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This is the main header file a user should include. + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_H_ + +// This file implements the following syntax: +// +// ON_CALL(mock_object.Method(...)) +// .With(...) ? +// .WillByDefault(...); +// +// where With() is optional and WillByDefault() must appear exactly +// once. +// +// EXPECT_CALL(mock_object.Method(...)) +// .With(...) ? +// .Times(...) ? +// .InSequence(...) * +// .WillOnce(...) * +// .WillRepeatedly(...) ? +// .RetiresOnSaturation() ? ; +// +// where all clauses are optional and WillOnce() can be repeated. + +#include "gmock/gmock-actions.h" +#include "gmock/gmock-cardinalities.h" +#include "gmock/gmock-generated-actions.h" +#include "gmock/gmock-generated-function-mockers.h" +#include "gmock/gmock-generated-nice-strict.h" +#include "gmock/gmock-generated-matchers.h" +#include "gmock/gmock-matchers.h" +#include "gmock/gmock-more-actions.h" +#include "gmock/gmock-more-matchers.h" +#include "gmock/internal/gmock-internal-utils.h" + +namespace testing { + +// Declares Google Mock flags that we want a user to use programmatically. +GMOCK_DECLARE_bool_(catch_leaked_mocks); +GMOCK_DECLARE_string_(verbose); + +// Initializes Google Mock. This must be called before running the +// tests. In particular, it parses the command line for the flags +// that Google Mock recognizes. Whenever a Google Mock flag is seen, +// it is removed from argv, and *argc is decremented. +// +// No value is returned. Instead, the Google Mock flag variables are +// updated. +// +// Since Google Test is needed for Google Mock to work, this function +// also initializes Google Test and parses its flags, if that hasn't +// been done. +GTEST_API_ void InitGoogleMock(int* argc, char** argv); + +// This overloaded version can be used in Windows programs compiled in +// UNICODE mode. +GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv); + +} // namespace testing + +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/custom/gmock-generated-actions.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/custom/gmock-generated-actions.h new file mode 100644 index 00000000000..7dc3b1ad541 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/custom/gmock-generated-actions.h @@ -0,0 +1,8 @@ +// This file was GENERATED by command: +// pump.py gmock-generated-actions.h.pump +// DO NOT EDIT BY HAND!!! + +#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ +#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ + +#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/custom/gmock-matchers.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/custom/gmock-matchers.h new file mode 100644 index 00000000000..f2efef91dbe --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/custom/gmock-matchers.h @@ -0,0 +1,39 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// ============================================================ +// An installation-specific extension point for gmock-matchers.h. +// ============================================================ +// +// Adds google3 callback support to CallableTraits. +// +#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ +#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ + +#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/custom/gmock-port.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/custom/gmock-port.h new file mode 100644 index 00000000000..9ce8bfe06bf --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/custom/gmock-port.h @@ -0,0 +1,46 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Injection point for custom user configurations. +// The following macros can be defined: +// +// Flag related macros: +// GMOCK_DECLARE_bool_(name) +// GMOCK_DECLARE_int32_(name) +// GMOCK_DECLARE_string_(name) +// GMOCK_DEFINE_bool_(name, default_val, doc) +// GMOCK_DEFINE_int32_(name, default_val, doc) +// GMOCK_DEFINE_string_(name, default_val, doc) +// +// ** Custom implementation starts here ** + +#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ +#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ + +#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/gmock-generated-internal-utils.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/gmock-generated-internal-utils.h new file mode 100644 index 00000000000..7811e43f87c --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/gmock-generated-internal-utils.h @@ -0,0 +1,279 @@ +// This file was GENERATED by command: +// pump.py gmock-generated-internal-utils.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file contains template meta-programming utility classes needed +// for implementing Google Mock. + +#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ +#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ + +#include "gmock/internal/gmock-port.h" + +namespace testing { + +template <typename T> +class Matcher; + +namespace internal { + +// An IgnoredValue object can be implicitly constructed from ANY value. +// This is used in implementing the IgnoreResult(a) action. +class IgnoredValue { + public: + // This constructor template allows any value to be implicitly + // converted to IgnoredValue. The object has no data member and + // doesn't try to remember anything about the argument. We + // deliberately omit the 'explicit' keyword in order to allow the + // conversion to be implicit. + template <typename T> + IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit) +}; + +// MatcherTuple<T>::type is a tuple type where each field is a Matcher +// for the corresponding field in tuple type T. +template <typename Tuple> +struct MatcherTuple; + +template <> +struct MatcherTuple< ::testing::tuple<> > { + typedef ::testing::tuple< > type; +}; + +template <typename A1> +struct MatcherTuple< ::testing::tuple<A1> > { + typedef ::testing::tuple<Matcher<A1> > type; +}; + +template <typename A1, typename A2> +struct MatcherTuple< ::testing::tuple<A1, A2> > { + typedef ::testing::tuple<Matcher<A1>, Matcher<A2> > type; +}; + +template <typename A1, typename A2, typename A3> +struct MatcherTuple< ::testing::tuple<A1, A2, A3> > { + typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3> > type; +}; + +template <typename A1, typename A2, typename A3, typename A4> +struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4> > { + typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, + Matcher<A4> > type; +}; + +template <typename A1, typename A2, typename A3, typename A4, typename A5> +struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5> > { + typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, + Matcher<A5> > type; +}; + +template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6> +struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6> > { + typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, + Matcher<A5>, Matcher<A6> > type; +}; + +template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7> +struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > { + typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, + Matcher<A5>, Matcher<A6>, Matcher<A7> > type; +}; + +template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8> +struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > { + typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, + Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8> > type; +}; + +template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8, typename A9> +struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > { + typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, + Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9> > type; +}; + +template <typename A1, typename A2, typename A3, typename A4, typename A5, + typename A6, typename A7, typename A8, typename A9, typename A10> +struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, + A10> > { + typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, + Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9>, + Matcher<A10> > type; +}; + +// Template struct Function<F>, where F must be a function type, contains +// the following typedefs: +// +// Result: the function's return type. +// ArgumentN: the type of the N-th argument, where N starts with 1. +// ArgumentTuple: the tuple type consisting of all parameters of F. +// ArgumentMatcherTuple: the tuple type consisting of Matchers for all +// parameters of F. +// MakeResultVoid: the function type obtained by substituting void +// for the return type of F. +// MakeResultIgnoredValue: +// the function type obtained by substituting Something +// for the return type of F. +template <typename F> +struct Function; + +template <typename R> +struct Function<R()> { + typedef R Result; + typedef ::testing::tuple<> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(); + typedef IgnoredValue MakeResultIgnoredValue(); +}; + +template <typename R, typename A1> +struct Function<R(A1)> + : Function<R()> { + typedef A1 Argument1; + typedef ::testing::tuple<A1> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(A1); + typedef IgnoredValue MakeResultIgnoredValue(A1); +}; + +template <typename R, typename A1, typename A2> +struct Function<R(A1, A2)> + : Function<R(A1)> { + typedef A2 Argument2; + typedef ::testing::tuple<A1, A2> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(A1, A2); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2); +}; + +template <typename R, typename A1, typename A2, typename A3> +struct Function<R(A1, A2, A3)> + : Function<R(A1, A2)> { + typedef A3 Argument3; + typedef ::testing::tuple<A1, A2, A3> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(A1, A2, A3); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3); +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4> +struct Function<R(A1, A2, A3, A4)> + : Function<R(A1, A2, A3)> { + typedef A4 Argument4; + typedef ::testing::tuple<A1, A2, A3, A4> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(A1, A2, A3, A4); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4); +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5> +struct Function<R(A1, A2, A3, A4, A5)> + : Function<R(A1, A2, A3, A4)> { + typedef A5 Argument5; + typedef ::testing::tuple<A1, A2, A3, A4, A5> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(A1, A2, A3, A4, A5); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5); +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6> +struct Function<R(A1, A2, A3, A4, A5, A6)> + : Function<R(A1, A2, A3, A4, A5)> { + typedef A6 Argument6; + typedef ::testing::tuple<A1, A2, A3, A4, A5, A6> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6); +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7> +struct Function<R(A1, A2, A3, A4, A5, A6, A7)> + : Function<R(A1, A2, A3, A4, A5, A6)> { + typedef A7 Argument7; + typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7); +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8> +struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8)> + : Function<R(A1, A2, A3, A4, A5, A6, A7)> { + typedef A8 Argument8; + typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8); +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8, typename A9> +struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> + : Function<R(A1, A2, A3, A4, A5, A6, A7, A8)> { + typedef A9 Argument9; + typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8, + A9); +}; + +template <typename R, typename A1, typename A2, typename A3, typename A4, + typename A5, typename A6, typename A7, typename A8, typename A9, + typename A10> +struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> + : Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> { + typedef A10 Argument10; + typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, + A10> ArgumentTuple; + typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; + typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8, + A9, A10); +}; + +} // namespace internal + +} // namespace testing + +#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/gmock-internal-utils.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/gmock-internal-utils.h new file mode 100644 index 00000000000..e2ddb05c91d --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -0,0 +1,511 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file defines some utilities useful for implementing Google +// Mock. They are subject to change without notice, so please DO NOT +// USE THEM IN USER CODE. + +#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ +#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ + +#include <stdio.h> +#include <ostream> // NOLINT +#include <string> + +#include "gmock/internal/gmock-generated-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" + +namespace testing { +namespace internal { + +// Converts an identifier name to a space-separated list of lower-case +// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is +// treated as one word. For example, both "FooBar123" and +// "foo_bar_123" are converted to "foo bar 123". +GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name); + +// PointeeOf<Pointer>::type is the type of a value pointed to by a +// Pointer, which can be either a smart pointer or a raw pointer. The +// following default implementation is for the case where Pointer is a +// smart pointer. +template <typename Pointer> +struct PointeeOf { + // Smart pointer classes define type element_type as the type of + // their pointees. + typedef typename Pointer::element_type type; +}; +// This specialization is for the raw pointer case. +template <typename T> +struct PointeeOf<T*> { typedef T type; }; // NOLINT + +// GetRawPointer(p) returns the raw pointer underlying p when p is a +// smart pointer, or returns p itself when p is already a raw pointer. +// The following default implementation is for the smart pointer case. +template <typename Pointer> +inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) { + return p.get(); +} +// This overloaded version is for the raw pointer case. +template <typename Element> +inline Element* GetRawPointer(Element* p) { return p; } + +// This comparator allows linked_ptr to be stored in sets. +template <typename T> +struct LinkedPtrLessThan { + bool operator()(const ::testing::internal::linked_ptr<T>& lhs, + const ::testing::internal::linked_ptr<T>& rhs) const { + return lhs.get() < rhs.get(); + } +}; + +// Symbian compilation can be done with wchar_t being either a native +// type or a typedef. Using Google Mock with OpenC without wchar_t +// should require the definition of _STLP_NO_WCHAR_T. +// +// MSVC treats wchar_t as a native type usually, but treats it as the +// same as unsigned short when the compiler option /Zc:wchar_t- is +// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t +// is a native type. +#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \ + (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)) +// wchar_t is a typedef. +#else +# define GMOCK_WCHAR_T_IS_NATIVE_ 1 +#endif + +// signed wchar_t and unsigned wchar_t are NOT in the C++ standard. +// Using them is a bad practice and not portable. So DON'T use them. +// +// Still, Google Mock is designed to work even if the user uses signed +// wchar_t or unsigned wchar_t (obviously, assuming the compiler +// supports them). +// +// To gcc, +// wchar_t == signed wchar_t != unsigned wchar_t == unsigned int +#ifdef __GNUC__ +// signed/unsigned wchar_t are valid types. +# define GMOCK_HAS_SIGNED_WCHAR_T_ 1 +#endif + +// In what follows, we use the term "kind" to indicate whether a type +// is bool, an integer type (excluding bool), a floating-point type, +// or none of them. This categorization is useful for determining +// when a matcher argument type can be safely converted to another +// type in the implementation of SafeMatcherCast. +enum TypeKind { + kBool, kInteger, kFloatingPoint, kOther +}; + +// KindOf<T>::value is the kind of type T. +template <typename T> struct KindOf { + enum { value = kOther }; // The default kind. +}; + +// This macro declares that the kind of 'type' is 'kind'. +#define GMOCK_DECLARE_KIND_(type, kind) \ + template <> struct KindOf<type> { enum { value = kind }; } + +GMOCK_DECLARE_KIND_(bool, kBool); + +// All standard integer types. +GMOCK_DECLARE_KIND_(char, kInteger); +GMOCK_DECLARE_KIND_(signed char, kInteger); +GMOCK_DECLARE_KIND_(unsigned char, kInteger); +GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(int, kInteger); +GMOCK_DECLARE_KIND_(unsigned int, kInteger); +GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT + +#if GMOCK_WCHAR_T_IS_NATIVE_ +GMOCK_DECLARE_KIND_(wchar_t, kInteger); +#endif + +// Non-standard integer types. +GMOCK_DECLARE_KIND_(Int64, kInteger); +GMOCK_DECLARE_KIND_(UInt64, kInteger); + +// All standard floating-point types. +GMOCK_DECLARE_KIND_(float, kFloatingPoint); +GMOCK_DECLARE_KIND_(double, kFloatingPoint); +GMOCK_DECLARE_KIND_(long double, kFloatingPoint); + +#undef GMOCK_DECLARE_KIND_ + +// Evaluates to the kind of 'type'. +#define GMOCK_KIND_OF_(type) \ + static_cast< ::testing::internal::TypeKind>( \ + ::testing::internal::KindOf<type>::value) + +// Evaluates to true iff integer type T is signed. +#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0) + +// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value +// is true iff arithmetic type From can be losslessly converted to +// arithmetic type To. +// +// It's the user's responsibility to ensure that both From and To are +// raw (i.e. has no CV modifier, is not a pointer, and is not a +// reference) built-in arithmetic types, kFromKind is the kind of +// From, and kToKind is the kind of To; the value is +// implementation-defined when the above pre-condition is violated. +template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To> +struct LosslessArithmeticConvertibleImpl : public false_type {}; + +// Converting bool to bool is lossless. +template <> +struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool> + : public true_type {}; // NOLINT + +// Converting bool to any integer type is lossless. +template <typename To> +struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To> + : public true_type {}; // NOLINT + +// Converting bool to any floating-point type is lossless. +template <typename To> +struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To> + : public true_type {}; // NOLINT + +// Converting an integer to bool is lossy. +template <typename From> +struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool> + : public false_type {}; // NOLINT + +// Converting an integer to another non-bool integer is lossless iff +// the target type's range encloses the source type's range. +template <typename From, typename To> +struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To> + : public bool_constant< + // When converting from a smaller size to a larger size, we are + // fine as long as we are not converting from signed to unsigned. + ((sizeof(From) < sizeof(To)) && + (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) || + // When converting between the same size, the signedness must match. + ((sizeof(From) == sizeof(To)) && + (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT + +#undef GMOCK_IS_SIGNED_ + +// Converting an integer to a floating-point type may be lossy, since +// the format of a floating-point number is implementation-defined. +template <typename From, typename To> +struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To> + : public false_type {}; // NOLINT + +// Converting a floating-point to bool is lossy. +template <typename From> +struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool> + : public false_type {}; // NOLINT + +// Converting a floating-point to an integer is lossy. +template <typename From, typename To> +struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To> + : public false_type {}; // NOLINT + +// Converting a floating-point to another floating-point is lossless +// iff the target type is at least as big as the source type. +template <typename From, typename To> +struct LosslessArithmeticConvertibleImpl< + kFloatingPoint, From, kFloatingPoint, To> + : public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT + +// LosslessArithmeticConvertible<From, To>::value is true iff arithmetic +// type From can be losslessly converted to arithmetic type To. +// +// It's the user's responsibility to ensure that both From and To are +// raw (i.e. has no CV modifier, is not a pointer, and is not a +// reference) built-in arithmetic types; the value is +// implementation-defined when the above pre-condition is violated. +template <typename From, typename To> +struct LosslessArithmeticConvertible + : public LosslessArithmeticConvertibleImpl< + GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT + +// This interface knows how to report a Google Mock failure (either +// non-fatal or fatal). +class FailureReporterInterface { + public: + // The type of a failure (either non-fatal or fatal). + enum FailureType { + kNonfatal, kFatal + }; + + virtual ~FailureReporterInterface() {} + + // Reports a failure that occurred at the given source file location. + virtual void ReportFailure(FailureType type, const char* file, int line, + const string& message) = 0; +}; + +// Returns the failure reporter used by Google Mock. +GTEST_API_ FailureReporterInterface* GetFailureReporter(); + +// Asserts that condition is true; aborts the process with the given +// message if condition is false. We cannot use LOG(FATAL) or CHECK() +// as Google Mock might be used to mock the log sink itself. We +// inline this function to prevent it from showing up in the stack +// trace. +inline void Assert(bool condition, const char* file, int line, + const string& msg) { + if (!condition) { + GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, + file, line, msg); + } +} +inline void Assert(bool condition, const char* file, int line) { + Assert(condition, file, line, "Assertion failed."); +} + +// Verifies that condition is true; generates a non-fatal failure if +// condition is false. +inline void Expect(bool condition, const char* file, int line, + const string& msg) { + if (!condition) { + GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal, + file, line, msg); + } +} +inline void Expect(bool condition, const char* file, int line) { + Expect(condition, file, line, "Expectation failed."); +} + +// Severity level of a log. +enum LogSeverity { + kInfo = 0, + kWarning = 1 +}; + +// Valid values for the --gmock_verbose flag. + +// All logs (informational and warnings) are printed. +const char kInfoVerbosity[] = "info"; +// Only warnings are printed. +const char kWarningVerbosity[] = "warning"; +// No logs are printed. +const char kErrorVerbosity[] = "error"; + +// Returns true iff a log with the given severity is visible according +// to the --gmock_verbose flag. +GTEST_API_ bool LogIsVisible(LogSeverity severity); + +// Prints the given message to stdout iff 'severity' >= the level +// specified by the --gmock_verbose flag. If stack_frames_to_skip >= +// 0, also prints the stack trace excluding the top +// stack_frames_to_skip frames. In opt mode, any positive +// stack_frames_to_skip is treated as 0, since we don't know which +// function calls will be inlined by the compiler and need to be +// conservative. +GTEST_API_ void Log(LogSeverity severity, + const string& message, + int stack_frames_to_skip); + +// TODO(wan@google.com): group all type utilities together. + +// Type traits. + +// is_reference<T>::value is non-zero iff T is a reference type. +template <typename T> struct is_reference : public false_type {}; +template <typename T> struct is_reference<T&> : public true_type {}; + +// type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type. +template <typename T1, typename T2> struct type_equals : public false_type {}; +template <typename T> struct type_equals<T, T> : public true_type {}; + +// remove_reference<T>::type removes the reference from type T, if any. +template <typename T> struct remove_reference { typedef T type; }; // NOLINT +template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT + +// DecayArray<T>::type turns an array type U[N] to const U* and preserves +// other types. Useful for saving a copy of a function argument. +template <typename T> struct DecayArray { typedef T type; }; // NOLINT +template <typename T, size_t N> struct DecayArray<T[N]> { + typedef const T* type; +}; +// Sometimes people use arrays whose size is not available at the use site +// (e.g. extern const char kNamePrefix[]). This specialization covers that +// case. +template <typename T> struct DecayArray<T[]> { + typedef const T* type; +}; + +// Disable MSVC warnings for infinite recursion, since in this case the +// the recursion is unreachable. +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4717) +#endif + +// Invalid<T>() is usable as an expression of type T, but will terminate +// the program with an assertion failure if actually run. This is useful +// when a value of type T is needed for compilation, but the statement +// will not really be executed (or we don't care if the statement +// crashes). +template <typename T> +inline T Invalid() { + Assert(false, "", -1, "Internal error: attempt to return invalid value"); + // This statement is unreachable, and would never terminate even if it + // could be reached. It is provided only to placate compiler warnings + // about missing return statements. + return Invalid<T>(); +} + +#ifdef _MSC_VER +# pragma warning(pop) +#endif + +// Given a raw type (i.e. having no top-level reference or const +// modifier) RawContainer that's either an STL-style container or a +// native array, class StlContainerView<RawContainer> has the +// following members: +// +// - type is a type that provides an STL-style container view to +// (i.e. implements the STL container concept for) RawContainer; +// - const_reference is a type that provides a reference to a const +// RawContainer; +// - ConstReference(raw_container) returns a const reference to an STL-style +// container view to raw_container, which is a RawContainer. +// - Copy(raw_container) returns an STL-style container view of a +// copy of raw_container, which is a RawContainer. +// +// This generic version is used when RawContainer itself is already an +// STL-style container. +template <class RawContainer> +class StlContainerView { + public: + typedef RawContainer type; + typedef const type& const_reference; + + static const_reference ConstReference(const RawContainer& container) { + // Ensures that RawContainer is not a const type. + testing::StaticAssertTypeEq<RawContainer, + GTEST_REMOVE_CONST_(RawContainer)>(); + return container; + } + static type Copy(const RawContainer& container) { return container; } +}; + +// This specialization is used when RawContainer is a native array type. +template <typename Element, size_t N> +class StlContainerView<Element[N]> { + public: + typedef GTEST_REMOVE_CONST_(Element) RawElement; + typedef internal::NativeArray<RawElement> type; + // NativeArray<T> can represent a native array either by value or by + // reference (selected by a constructor argument), so 'const type' + // can be used to reference a const native array. We cannot + // 'typedef const type& const_reference' here, as that would mean + // ConstReference() has to return a reference to a local variable. + typedef const type const_reference; + + static const_reference ConstReference(const Element (&array)[N]) { + // Ensures that Element is not a const type. + testing::StaticAssertTypeEq<Element, RawElement>(); +#if GTEST_OS_SYMBIAN + // The Nokia Symbian compiler confuses itself in template instantiation + // for this call without the cast to Element*: + // function call '[testing::internal::NativeArray<char *>].NativeArray( + // {lval} const char *[4], long, testing::internal::RelationToSource)' + // does not match + // 'testing::internal::NativeArray<char *>::NativeArray( + // char *const *, unsigned int, testing::internal::RelationToSource)' + // (instantiating: 'testing::internal::ContainsMatcherImpl + // <const char * (&)[4]>::Matches(const char * (&)[4]) const') + // (instantiating: 'testing::internal::StlContainerView<char *[4]>:: + // ConstReference(const char * (&)[4])') + // (and though the N parameter type is mismatched in the above explicit + // conversion of it doesn't help - only the conversion of the array). + return type(const_cast<Element*>(&array[0]), N, + RelationToSourceReference()); +#else + return type(array, N, RelationToSourceReference()); +#endif // GTEST_OS_SYMBIAN + } + static type Copy(const Element (&array)[N]) { +#if GTEST_OS_SYMBIAN + return type(const_cast<Element*>(&array[0]), N, RelationToSourceCopy()); +#else + return type(array, N, RelationToSourceCopy()); +#endif // GTEST_OS_SYMBIAN + } +}; + +// This specialization is used when RawContainer is a native array +// represented as a (pointer, size) tuple. +template <typename ElementPointer, typename Size> +class StlContainerView< ::testing::tuple<ElementPointer, Size> > { + public: + typedef GTEST_REMOVE_CONST_( + typename internal::PointeeOf<ElementPointer>::type) RawElement; + typedef internal::NativeArray<RawElement> type; + typedef const type const_reference; + + static const_reference ConstReference( + const ::testing::tuple<ElementPointer, Size>& array) { + return type(get<0>(array), get<1>(array), RelationToSourceReference()); + } + static type Copy(const ::testing::tuple<ElementPointer, Size>& array) { + return type(get<0>(array), get<1>(array), RelationToSourceCopy()); + } +}; + +// The following specialization prevents the user from instantiating +// StlContainer with a reference type. +template <typename T> class StlContainerView<T&>; + +// A type transform to remove constness from the first part of a pair. +// Pairs like that are used as the value_type of associative containers, +// and this transform produces a similar but assignable pair. +template <typename T> +struct RemoveConstFromKey { + typedef T type; +}; + +// Partially specialized to remove constness from std::pair<const K, V>. +template <typename K, typename V> +struct RemoveConstFromKey<std::pair<const K, V> > { + typedef std::pair<K, V> type; +}; + +// Mapping from booleans to types. Similar to boost::bool_<kValue> and +// std::integral_constant<bool, kValue>. +template <bool kValue> +struct BooleanConstant {}; + +} // namespace internal +} // namespace testing + +#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ + diff --git a/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/gmock-port.h b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/gmock-port.h new file mode 100644 index 00000000000..63f4a6802e8 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/include/gmock/internal/gmock-port.h @@ -0,0 +1,91 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vadimb@google.com (Vadim Berman) +// +// Low-level types and utilities for porting Google Mock to various +// platforms. All macros ending with _ and symbols defined in an +// internal namespace are subject to change without notice. Code +// outside Google Mock MUST NOT USE THEM DIRECTLY. Macros that don't +// end with _ are part of Google Mock's public API and can be used by +// code outside Google Mock. + +#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ +#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ + +#include <assert.h> +#include <stdlib.h> +#include <iostream> + +// Most of the utilities needed for porting Google Mock are also +// required for Google Test and are defined in gtest-port.h. +// +// Note to maintainers: to reduce code duplication, prefer adding +// portability utilities to Google Test's gtest-port.h instead of +// here, as Google Mock depends on Google Test. Only add a utility +// here if it's truly specific to Google Mock. +#include "gtest/internal/gtest-linked_ptr.h" +#include "gtest/internal/gtest-port.h" +#include "gmock/internal/custom/gmock-port.h" + +// To avoid conditional compilation everywhere, we make it +// gmock-port.h's responsibility to #include the header implementing +// tr1/tuple. gmock-port.h does this via gtest-port.h, which is +// guaranteed to pull in the tuple header. + +// For MS Visual C++, check the compiler version. At least VS 2003 is +// required to compile Google Mock. +#if defined(_MSC_VER) && _MSC_VER < 1310 +# error "At least Visual C++ 2003 (7.1) is required to compile Google Mock." +#endif + +// Macro for referencing flags. This is public as we want the user to +// use this syntax to reference Google Mock flags. +#define GMOCK_FLAG(name) FLAGS_gmock_##name + +#if !defined(GMOCK_DECLARE_bool_) + +// Macros for declaring flags. +#define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) +#define GMOCK_DECLARE_int32_(name) \ + extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) +#define GMOCK_DECLARE_string_(name) \ + extern GTEST_API_ ::std::string GMOCK_FLAG(name) + +// Macros for defining flags. +#define GMOCK_DEFINE_bool_(name, default_val, doc) \ + GTEST_API_ bool GMOCK_FLAG(name) = (default_val) +#define GMOCK_DEFINE_int32_(name, default_val, doc) \ + GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val) +#define GMOCK_DEFINE_string_(name, default_val, doc) \ + GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val) + +#endif // !defined(GMOCK_DECLARE_bool_) + +#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ diff --git a/gnu/llvm/utils/unittest/googlemock/src/gmock-all.cc b/gnu/llvm/utils/unittest/googlemock/src/gmock-all.cc new file mode 100644 index 00000000000..7aebce7afef --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/src/gmock-all.cc @@ -0,0 +1,47 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Google C++ Mocking Framework (Google Mock) +// +// This file #includes all Google Mock implementation .cc files. The +// purpose is to allow a user to build Google Mock by compiling this +// file alone. + +// This line ensures that gmock.h can be compiled on its own, even +// when it's fused. +#include "gmock/gmock.h" + +// The following lines pull in the real gmock *.cc files. +#include "src/gmock-cardinalities.cc" +#include "src/gmock-internal-utils.cc" +#include "src/gmock-matchers.cc" +#include "src/gmock-spec-builders.cc" +#include "src/gmock.cc" diff --git a/gnu/llvm/utils/unittest/googlemock/src/gmock-cardinalities.cc b/gnu/llvm/utils/unittest/googlemock/src/gmock-cardinalities.cc new file mode 100644 index 00000000000..50ec7286eeb --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/src/gmock-cardinalities.cc @@ -0,0 +1,156 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements cardinalities. + +#include "gmock/gmock-cardinalities.h" + +#include <limits.h> +#include <ostream> // NOLINT +#include <sstream> +#include <string> +#include "gmock/internal/gmock-internal-utils.h" +#include "gtest/gtest.h" + +namespace testing { + +namespace { + +// Implements the Between(m, n) cardinality. +class BetweenCardinalityImpl : public CardinalityInterface { + public: + BetweenCardinalityImpl(int min, int max) + : min_(min >= 0 ? min : 0), + max_(max >= min_ ? max : min_) { + std::stringstream ss; + if (min < 0) { + ss << "The invocation lower bound must be >= 0, " + << "but is actually " << min << "."; + internal::Expect(false, __FILE__, __LINE__, ss.str()); + } else if (max < 0) { + ss << "The invocation upper bound must be >= 0, " + << "but is actually " << max << "."; + internal::Expect(false, __FILE__, __LINE__, ss.str()); + } else if (min > max) { + ss << "The invocation upper bound (" << max + << ") must be >= the invocation lower bound (" << min + << ")."; + internal::Expect(false, __FILE__, __LINE__, ss.str()); + } + } + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + virtual int ConservativeLowerBound() const { return min_; } + virtual int ConservativeUpperBound() const { return max_; } + + virtual bool IsSatisfiedByCallCount(int call_count) const { + return min_ <= call_count && call_count <= max_; + } + + virtual bool IsSaturatedByCallCount(int call_count) const { + return call_count >= max_; + } + + virtual void DescribeTo(::std::ostream* os) const; + + private: + const int min_; + const int max_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl); +}; + +// Formats "n times" in a human-friendly way. +inline internal::string FormatTimes(int n) { + if (n == 1) { + return "once"; + } else if (n == 2) { + return "twice"; + } else { + std::stringstream ss; + ss << n << " times"; + return ss.str(); + } +} + +// Describes the Between(m, n) cardinality in human-friendly text. +void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const { + if (min_ == 0) { + if (max_ == 0) { + *os << "never called"; + } else if (max_ == INT_MAX) { + *os << "called any number of times"; + } else { + *os << "called at most " << FormatTimes(max_); + } + } else if (min_ == max_) { + *os << "called " << FormatTimes(min_); + } else if (max_ == INT_MAX) { + *os << "called at least " << FormatTimes(min_); + } else { + // 0 < min_ < max_ < INT_MAX + *os << "called between " << min_ << " and " << max_ << " times"; + } +} + +} // Unnamed namespace + +// Describes the given call count to an ostream. +void Cardinality::DescribeActualCallCountTo(int actual_call_count, + ::std::ostream* os) { + if (actual_call_count > 0) { + *os << "called " << FormatTimes(actual_call_count); + } else { + *os << "never called"; + } +} + +// Creates a cardinality that allows at least n calls. +GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); } + +// Creates a cardinality that allows at most n calls. +GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); } + +// Creates a cardinality that allows any number of calls. +GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); } + +// Creates a cardinality that allows between min and max calls. +GTEST_API_ Cardinality Between(int min, int max) { + return Cardinality(new BetweenCardinalityImpl(min, max)); +} + +// Creates a cardinality that allows exactly n calls. +GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); } + +} // namespace testing diff --git a/gnu/llvm/utils/unittest/googlemock/src/gmock-internal-utils.cc b/gnu/llvm/utils/unittest/googlemock/src/gmock-internal-utils.cc new file mode 100644 index 00000000000..fb5308018a7 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/src/gmock-internal-utils.cc @@ -0,0 +1,174 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file defines some utilities useful for implementing Google +// Mock. They are subject to change without notice, so please DO NOT +// USE THEM IN USER CODE. + +#include "gmock/internal/gmock-internal-utils.h" + +#include <ctype.h> +#include <ostream> // NOLINT +#include <string> +#include "gmock/gmock.h" +#include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" + +namespace testing { +namespace internal { + +// Converts an identifier name to a space-separated list of lower-case +// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is +// treated as one word. For example, both "FooBar123" and +// "foo_bar_123" are converted to "foo bar 123". +GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) { + string result; + char prev_char = '\0'; + for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) { + // We don't care about the current locale as the input is + // guaranteed to be a valid C++ identifier name. + const bool starts_new_word = IsUpper(*p) || + (!IsAlpha(prev_char) && IsLower(*p)) || + (!IsDigit(prev_char) && IsDigit(*p)); + + if (IsAlNum(*p)) { + if (starts_new_word && result != "") + result += ' '; + result += ToLower(*p); + } + } + return result; +} + +// This class reports Google Mock failures as Google Test failures. A +// user can define another class in a similar fashion if he intends to +// use Google Mock with a testing framework other than Google Test. +class GoogleTestFailureReporter : public FailureReporterInterface { + public: + virtual void ReportFailure(FailureType type, const char* file, int line, + const string& message) { + AssertHelper(type == kFatal ? + TestPartResult::kFatalFailure : + TestPartResult::kNonFatalFailure, + file, + line, + message.c_str()) = Message(); + if (type == kFatal) { + posix::Abort(); + } + } +}; + +// Returns the global failure reporter. Will create a +// GoogleTestFailureReporter and return it the first time called. +GTEST_API_ FailureReporterInterface* GetFailureReporter() { + // Points to the global failure reporter used by Google Mock. gcc + // guarantees that the following use of failure_reporter is + // thread-safe. We may need to add additional synchronization to + // protect failure_reporter if we port Google Mock to other + // compilers. + static FailureReporterInterface* const failure_reporter = + new GoogleTestFailureReporter(); + return failure_reporter; +} + +// Protects global resources (stdout in particular) used by Log(). +static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex); + +// Returns true iff a log with the given severity is visible according +// to the --gmock_verbose flag. +GTEST_API_ bool LogIsVisible(LogSeverity severity) { + if (GMOCK_FLAG(verbose) == kInfoVerbosity) { + // Always show the log if --gmock_verbose=info. + return true; + } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) { + // Always hide it if --gmock_verbose=error. + return false; + } else { + // If --gmock_verbose is neither "info" nor "error", we treat it + // as "warning" (its default value). + return severity == kWarning; + } +} + +// Prints the given message to stdout iff 'severity' >= the level +// specified by the --gmock_verbose flag. If stack_frames_to_skip >= +// 0, also prints the stack trace excluding the top +// stack_frames_to_skip frames. In opt mode, any positive +// stack_frames_to_skip is treated as 0, since we don't know which +// function calls will be inlined by the compiler and need to be +// conservative. +GTEST_API_ void Log(LogSeverity severity, + const string& message, + int stack_frames_to_skip) { + if (!LogIsVisible(severity)) + return; + + // Ensures that logs from different threads don't interleave. + MutexLock l(&g_log_mutex); + + // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a + // macro. + + if (severity == kWarning) { + // Prints a GMOCK WARNING marker to make the warnings easily searchable. + std::cout << "\nGMOCK WARNING:"; + } + // Pre-pends a new-line to message if it doesn't start with one. + if (message.empty() || message[0] != '\n') { + std::cout << "\n"; + } + std::cout << message; + if (stack_frames_to_skip >= 0) { +#ifdef NDEBUG + // In opt mode, we have to be conservative and skip no stack frame. + const int actual_to_skip = 0; +#else + // In dbg mode, we can do what the caller tell us to do (plus one + // for skipping this function's stack frame). + const int actual_to_skip = stack_frames_to_skip + 1; +#endif // NDEBUG + + // Appends a new-line to message if it doesn't end with one. + if (!message.empty() && *message.rbegin() != '\n') { + std::cout << "\n"; + } + std::cout << "Stack trace:\n" + << ::testing::internal::GetCurrentOsStackTraceExceptTop( + ::testing::UnitTest::GetInstance(), actual_to_skip); + } + std::cout << ::std::flush; +} + +} // namespace internal +} // namespace testing diff --git a/gnu/llvm/utils/unittest/googlemock/src/gmock-matchers.cc b/gnu/llvm/utils/unittest/googlemock/src/gmock-matchers.cc new file mode 100644 index 00000000000..e7424510fca --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/src/gmock-matchers.cc @@ -0,0 +1,498 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements Matcher<const string&>, Matcher<string>, and +// utilities for defining matchers. + +#include "gmock/gmock-matchers.h" +#include "gmock/gmock-generated-matchers.h" + +#include <string.h> +#include <sstream> +#include <string> + +namespace testing { + +// Constructs a matcher that matches a const string& whose value is +// equal to s. +Matcher<const internal::string&>::Matcher(const internal::string& s) { + *this = Eq(s); +} + +// Constructs a matcher that matches a const string& whose value is +// equal to s. +Matcher<const internal::string&>::Matcher(const char* s) { + *this = Eq(internal::string(s)); +} + +// Constructs a matcher that matches a string whose value is equal to s. +Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); } + +// Constructs a matcher that matches a string whose value is equal to s. +Matcher<internal::string>::Matcher(const char* s) { + *this = Eq(internal::string(s)); +} + +#if GTEST_HAS_STRING_PIECE_ +// Constructs a matcher that matches a const StringPiece& whose value is +// equal to s. +Matcher<const StringPiece&>::Matcher(const internal::string& s) { + *this = Eq(s); +} + +// Constructs a matcher that matches a const StringPiece& whose value is +// equal to s. +Matcher<const StringPiece&>::Matcher(const char* s) { + *this = Eq(internal::string(s)); +} + +// Constructs a matcher that matches a const StringPiece& whose value is +// equal to s. +Matcher<const StringPiece&>::Matcher(StringPiece s) { + *this = Eq(s.ToString()); +} + +// Constructs a matcher that matches a StringPiece whose value is equal to s. +Matcher<StringPiece>::Matcher(const internal::string& s) { + *this = Eq(s); +} + +// Constructs a matcher that matches a StringPiece whose value is equal to s. +Matcher<StringPiece>::Matcher(const char* s) { + *this = Eq(internal::string(s)); +} + +// Constructs a matcher that matches a StringPiece whose value is equal to s. +Matcher<StringPiece>::Matcher(StringPiece s) { + *this = Eq(s.ToString()); +} +#endif // GTEST_HAS_STRING_PIECE_ + +namespace internal { + +// Joins a vector of strings as if they are fields of a tuple; returns +// the joined string. +GTEST_API_ string JoinAsTuple(const Strings& fields) { + switch (fields.size()) { + case 0: + return ""; + case 1: + return fields[0]; + default: + string result = "(" + fields[0]; + for (size_t i = 1; i < fields.size(); i++) { + result += ", "; + result += fields[i]; + } + result += ")"; + return result; + } +} + +// Returns the description for a matcher defined using the MATCHER*() +// macro where the user-supplied description string is "", if +// 'negation' is false; otherwise returns the description of the +// negation of the matcher. 'param_values' contains a list of strings +// that are the print-out of the matcher's parameters. +GTEST_API_ string FormatMatcherDescription(bool negation, + const char* matcher_name, + const Strings& param_values) { + string result = ConvertIdentifierNameToWords(matcher_name); + if (param_values.size() >= 1) + result += " " + JoinAsTuple(param_values); + return negation ? "not (" + result + ")" : result; +} + +// FindMaxBipartiteMatching and its helper class. +// +// Uses the well-known Ford-Fulkerson max flow method to find a maximum +// bipartite matching. Flow is considered to be from left to right. +// There is an implicit source node that is connected to all of the left +// nodes, and an implicit sink node that is connected to all of the +// right nodes. All edges have unit capacity. +// +// Neither the flow graph nor the residual flow graph are represented +// explicitly. Instead, they are implied by the information in 'graph' and +// a vector<int> called 'left_' whose elements are initialized to the +// value kUnused. This represents the initial state of the algorithm, +// where the flow graph is empty, and the residual flow graph has the +// following edges: +// - An edge from source to each left_ node +// - An edge from each right_ node to sink +// - An edge from each left_ node to each right_ node, if the +// corresponding edge exists in 'graph'. +// +// When the TryAugment() method adds a flow, it sets left_[l] = r for some +// nodes l and r. This induces the following changes: +// - The edges (source, l), (l, r), and (r, sink) are added to the +// flow graph. +// - The same three edges are removed from the residual flow graph. +// - The reverse edges (l, source), (r, l), and (sink, r) are added +// to the residual flow graph, which is a directional graph +// representing unused flow capacity. +// +// When the method augments a flow (moving left_[l] from some r1 to some +// other r2), this can be thought of as "undoing" the above steps with +// respect to r1 and "redoing" them with respect to r2. +// +// It bears repeating that the flow graph and residual flow graph are +// never represented explicitly, but can be derived by looking at the +// information in 'graph' and in left_. +// +// As an optimization, there is a second vector<int> called right_ which +// does not provide any new information. Instead, it enables more +// efficient queries about edges entering or leaving the right-side nodes +// of the flow or residual flow graphs. The following invariants are +// maintained: +// +// left[l] == kUnused or right[left[l]] == l +// right[r] == kUnused or left[right[r]] == r +// +// . [ source ] . +// . ||| . +// . ||| . +// . ||\--> left[0]=1 ---\ right[0]=-1 ----\ . +// . || | | . +// . |\---> left[1]=-1 \--> right[1]=0 ---\| . +// . | || . +// . \----> left[2]=2 ------> right[2]=2 --\|| . +// . ||| . +// . elements matchers vvv . +// . [ sink ] . +// +// See Also: +// [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method". +// "Introduction to Algorithms (Second ed.)", pp. 651-664. +// [2] "Ford-Fulkerson algorithm", Wikipedia, +// 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm' +class MaxBipartiteMatchState { + public: + explicit MaxBipartiteMatchState(const MatchMatrix& graph) + : graph_(&graph), + left_(graph_->LhsSize(), kUnused), + right_(graph_->RhsSize(), kUnused) { + } + + // Returns the edges of a maximal match, each in the form {left, right}. + ElementMatcherPairs Compute() { + // 'seen' is used for path finding { 0: unseen, 1: seen }. + ::std::vector<char> seen; + // Searches the residual flow graph for a path from each left node to + // the sink in the residual flow graph, and if one is found, add flow + // to the graph. It's okay to search through the left nodes once. The + // edge from the implicit source node to each previously-visited left + // node will have flow if that left node has any path to the sink + // whatsoever. Subsequent augmentations can only add flow to the + // network, and cannot take away that previous flow unit from the source. + // Since the source-to-left edge can only carry one flow unit (or, + // each element can be matched to only one matcher), there is no need + // to visit the left nodes more than once looking for augmented paths. + // The flow is known to be possible or impossible by looking at the + // node once. + for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) { + // Reset the path-marking vector and try to find a path from + // source to sink starting at the left_[ilhs] node. + GTEST_CHECK_(left_[ilhs] == kUnused) + << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs]; + // 'seen' initialized to 'graph_->RhsSize()' copies of 0. + seen.assign(graph_->RhsSize(), 0); + TryAugment(ilhs, &seen); + } + ElementMatcherPairs result; + for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) { + size_t irhs = left_[ilhs]; + if (irhs == kUnused) continue; + result.push_back(ElementMatcherPair(ilhs, irhs)); + } + return result; + } + + private: + static const size_t kUnused = static_cast<size_t>(-1); + + // Perform a depth-first search from left node ilhs to the sink. If a + // path is found, flow is added to the network by linking the left and + // right vector elements corresponding each segment of the path. + // Returns true if a path to sink was found, which means that a unit of + // flow was added to the network. The 'seen' vector elements correspond + // to right nodes and are marked to eliminate cycles from the search. + // + // Left nodes will only be explored at most once because they + // are accessible from at most one right node in the residual flow + // graph. + // + // Note that left_[ilhs] is the only element of left_ that TryAugment will + // potentially transition from kUnused to another value. Any other + // left_ element holding kUnused before TryAugment will be holding it + // when TryAugment returns. + // + bool TryAugment(size_t ilhs, ::std::vector<char>* seen) { + for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { + if ((*seen)[irhs]) + continue; + if (!graph_->HasEdge(ilhs, irhs)) + continue; + // There's an available edge from ilhs to irhs. + (*seen)[irhs] = 1; + // Next a search is performed to determine whether + // this edge is a dead end or leads to the sink. + // + // right_[irhs] == kUnused means that there is residual flow from + // right node irhs to the sink, so we can use that to finish this + // flow path and return success. + // + // Otherwise there is residual flow to some ilhs. We push flow + // along that path and call ourselves recursively to see if this + // ultimately leads to sink. + if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) { + // Add flow from left_[ilhs] to right_[irhs]. + left_[ilhs] = irhs; + right_[irhs] = ilhs; + return true; + } + } + return false; + } + + const MatchMatrix* graph_; // not owned + // Each element of the left_ vector represents a left hand side node + // (i.e. an element) and each element of right_ is a right hand side + // node (i.e. a matcher). The values in the left_ vector indicate + // outflow from that node to a node on the the right_ side. The values + // in the right_ indicate inflow, and specify which left_ node is + // feeding that right_ node, if any. For example, left_[3] == 1 means + // there's a flow from element #3 to matcher #1. Such a flow would also + // be redundantly represented in the right_ vector as right_[1] == 3. + // Elements of left_ and right_ are either kUnused or mutually + // referent. Mutually referent means that left_[right_[i]] = i and + // right_[left_[i]] = i. + ::std::vector<size_t> left_; + ::std::vector<size_t> right_; + + GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState); +}; + +const size_t MaxBipartiteMatchState::kUnused; + +GTEST_API_ ElementMatcherPairs +FindMaxBipartiteMatching(const MatchMatrix& g) { + return MaxBipartiteMatchState(g).Compute(); +} + +static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs, + ::std::ostream* stream) { + typedef ElementMatcherPairs::const_iterator Iter; + ::std::ostream& os = *stream; + os << "{"; + const char *sep = ""; + for (Iter it = pairs.begin(); it != pairs.end(); ++it) { + os << sep << "\n (" + << "element #" << it->first << ", " + << "matcher #" << it->second << ")"; + sep = ","; + } + os << "\n}"; +} + +// Tries to find a pairing, and explains the result. +GTEST_API_ bool FindPairing(const MatchMatrix& matrix, + MatchResultListener* listener) { + ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix); + + size_t max_flow = matches.size(); + bool result = (max_flow == matrix.RhsSize()); + + if (!result) { + if (listener->IsInterested()) { + *listener << "where no permutation of the elements can " + "satisfy all matchers, and the closest match is " + << max_flow << " of " << matrix.RhsSize() + << " matchers with the pairings:\n"; + LogElementMatcherPairVec(matches, listener->stream()); + } + return false; + } + + if (matches.size() > 1) { + if (listener->IsInterested()) { + const char *sep = "where:\n"; + for (size_t mi = 0; mi < matches.size(); ++mi) { + *listener << sep << " - element #" << matches[mi].first + << " is matched by matcher #" << matches[mi].second; + sep = ",\n"; + } + } + } + return true; +} + +bool MatchMatrix::NextGraph() { + for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) { + for (size_t irhs = 0; irhs < RhsSize(); ++irhs) { + char& b = matched_[SpaceIndex(ilhs, irhs)]; + if (!b) { + b = 1; + return true; + } + b = 0; + } + } + return false; +} + +void MatchMatrix::Randomize() { + for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) { + for (size_t irhs = 0; irhs < RhsSize(); ++irhs) { + char& b = matched_[SpaceIndex(ilhs, irhs)]; + b = static_cast<char>(rand() & 1); // NOLINT + } + } +} + +string MatchMatrix::DebugString() const { + ::std::stringstream ss; + const char *sep = ""; + for (size_t i = 0; i < LhsSize(); ++i) { + ss << sep; + for (size_t j = 0; j < RhsSize(); ++j) { + ss << HasEdge(i, j); + } + sep = ";"; + } + return ss.str(); +} + +void UnorderedElementsAreMatcherImplBase::DescribeToImpl( + ::std::ostream* os) const { + if (matcher_describers_.empty()) { + *os << "is empty"; + return; + } + if (matcher_describers_.size() == 1) { + *os << "has " << Elements(1) << " and that element "; + matcher_describers_[0]->DescribeTo(os); + return; + } + *os << "has " << Elements(matcher_describers_.size()) + << " and there exists some permutation of elements such that:\n"; + const char* sep = ""; + for (size_t i = 0; i != matcher_describers_.size(); ++i) { + *os << sep << " - element #" << i << " "; + matcher_describers_[i]->DescribeTo(os); + sep = ", and\n"; + } +} + +void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl( + ::std::ostream* os) const { + if (matcher_describers_.empty()) { + *os << "isn't empty"; + return; + } + if (matcher_describers_.size() == 1) { + *os << "doesn't have " << Elements(1) + << ", or has " << Elements(1) << " that "; + matcher_describers_[0]->DescribeNegationTo(os); + return; + } + *os << "doesn't have " << Elements(matcher_describers_.size()) + << ", or there exists no permutation of elements such that:\n"; + const char* sep = ""; + for (size_t i = 0; i != matcher_describers_.size(); ++i) { + *os << sep << " - element #" << i << " "; + matcher_describers_[i]->DescribeTo(os); + sep = ", and\n"; + } +} + +// Checks that all matchers match at least one element, and that all +// elements match at least one matcher. This enables faster matching +// and better error reporting. +// Returns false, writing an explanation to 'listener', if and only +// if the success criteria are not met. +bool UnorderedElementsAreMatcherImplBase:: +VerifyAllElementsAndMatchersAreMatched( + const ::std::vector<string>& element_printouts, + const MatchMatrix& matrix, + MatchResultListener* listener) const { + bool result = true; + ::std::vector<char> element_matched(matrix.LhsSize(), 0); + ::std::vector<char> matcher_matched(matrix.RhsSize(), 0); + + for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) { + for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) { + char matched = matrix.HasEdge(ilhs, irhs); + element_matched[ilhs] |= matched; + matcher_matched[irhs] |= matched; + } + } + + { + const char* sep = + "where the following matchers don't match any elements:\n"; + for (size_t mi = 0; mi < matcher_matched.size(); ++mi) { + if (matcher_matched[mi]) + continue; + result = false; + if (listener->IsInterested()) { + *listener << sep << "matcher #" << mi << ": "; + matcher_describers_[mi]->DescribeTo(listener->stream()); + sep = ",\n"; + } + } + } + + { + const char* sep = + "where the following elements don't match any matchers:\n"; + const char* outer_sep = ""; + if (!result) { + outer_sep = "\nand "; + } + for (size_t ei = 0; ei < element_matched.size(); ++ei) { + if (element_matched[ei]) + continue; + result = false; + if (listener->IsInterested()) { + *listener << outer_sep << sep << "element #" << ei << ": " + << element_printouts[ei]; + sep = ",\n"; + outer_sep = ""; + } + } + } + return result; +} + +} // namespace internal +} // namespace testing diff --git a/gnu/llvm/utils/unittest/googlemock/src/gmock-spec-builders.cc b/gnu/llvm/utils/unittest/googlemock/src/gmock-spec-builders.cc new file mode 100644 index 00000000000..95513420707 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/src/gmock-spec-builders.cc @@ -0,0 +1,823 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements the spec builder syntax (ON_CALL and +// EXPECT_CALL). + +#include "gmock/gmock-spec-builders.h" + +#include <stdlib.h> +#include <iostream> // NOLINT +#include <map> +#include <set> +#include <string> +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC +# include <unistd.h> // NOLINT +#endif + +namespace testing { +namespace internal { + +// Protects the mock object registry (in class Mock), all function +// mockers, and all expectations. +GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex); + +// Logs a message including file and line number information. +GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, + const char* file, int line, + const string& message) { + ::std::ostringstream s; + s << file << ":" << line << ": " << message << ::std::endl; + Log(severity, s.str(), 0); +} + +// Constructs an ExpectationBase object. +ExpectationBase::ExpectationBase(const char* a_file, + int a_line, + const string& a_source_text) + : file_(a_file), + line_(a_line), + source_text_(a_source_text), + cardinality_specified_(false), + cardinality_(Exactly(1)), + call_count_(0), + retired_(false), + extra_matcher_specified_(false), + repeated_action_specified_(false), + retires_on_saturation_(false), + last_clause_(kNone), + action_count_checked_(false) {} + +// Destructs an ExpectationBase object. +ExpectationBase::~ExpectationBase() {} + +// Explicitly specifies the cardinality of this expectation. Used by +// the subclasses to implement the .Times() clause. +void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) { + cardinality_specified_ = true; + cardinality_ = a_cardinality; +} + +// Retires all pre-requisites of this expectation. +void ExpectationBase::RetireAllPreRequisites() + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + if (is_retired()) { + // We can take this short-cut as we never retire an expectation + // until we have retired all its pre-requisites. + return; + } + + for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); + it != immediate_prerequisites_.end(); ++it) { + ExpectationBase* const prerequisite = it->expectation_base().get(); + if (!prerequisite->is_retired()) { + prerequisite->RetireAllPreRequisites(); + prerequisite->Retire(); + } + } +} + +// Returns true iff all pre-requisites of this expectation have been +// satisfied. +bool ExpectationBase::AllPrerequisitesAreSatisfied() const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); + it != immediate_prerequisites_.end(); ++it) { + if (!(it->expectation_base()->IsSatisfied()) || + !(it->expectation_base()->AllPrerequisitesAreSatisfied())) + return false; + } + return true; +} + +// Adds unsatisfied pre-requisites of this expectation to 'result'. +void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); + it != immediate_prerequisites_.end(); ++it) { + if (it->expectation_base()->IsSatisfied()) { + // If *it is satisfied and has a call count of 0, some of its + // pre-requisites may not be satisfied yet. + if (it->expectation_base()->call_count_ == 0) { + it->expectation_base()->FindUnsatisfiedPrerequisites(result); + } + } else { + // Now that we know *it is unsatisfied, we are not so interested + // in whether its pre-requisites are satisfied. Therefore we + // don't recursively call FindUnsatisfiedPrerequisites() here. + *result += *it; + } + } +} + +// Describes how many times a function call matching this +// expectation has occurred. +void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + + // Describes how many times the function is expected to be called. + *os << " Expected: to be "; + cardinality().DescribeTo(os); + *os << "\n Actual: "; + Cardinality::DescribeActualCallCountTo(call_count(), os); + + // Describes the state of the expectation (e.g. is it satisfied? + // is it active?). + *os << " - " << (IsOverSaturated() ? "over-saturated" : + IsSaturated() ? "saturated" : + IsSatisfied() ? "satisfied" : "unsatisfied") + << " and " + << (is_retired() ? "retired" : "active"); +} + +// Checks the action count (i.e. the number of WillOnce() and +// WillRepeatedly() clauses) against the cardinality if this hasn't +// been done before. Prints a warning if there are too many or too +// few actions. +void ExpectationBase::CheckActionCountIfNotDone() const + GTEST_LOCK_EXCLUDED_(mutex_) { + bool should_check = false; + { + MutexLock l(&mutex_); + if (!action_count_checked_) { + action_count_checked_ = true; + should_check = true; + } + } + + if (should_check) { + if (!cardinality_specified_) { + // The cardinality was inferred - no need to check the action + // count against it. + return; + } + + // The cardinality was explicitly specified. + const int action_count = static_cast<int>(untyped_actions_.size()); + const int upper_bound = cardinality().ConservativeUpperBound(); + const int lower_bound = cardinality().ConservativeLowerBound(); + bool too_many; // True if there are too many actions, or false + // if there are too few. + if (action_count > upper_bound || + (action_count == upper_bound && repeated_action_specified_)) { + too_many = true; + } else if (0 < action_count && action_count < lower_bound && + !repeated_action_specified_) { + too_many = false; + } else { + return; + } + + ::std::stringstream ss; + DescribeLocationTo(&ss); + ss << "Too " << (too_many ? "many" : "few") + << " actions specified in " << source_text() << "...\n" + << "Expected to be "; + cardinality().DescribeTo(&ss); + ss << ", but has " << (too_many ? "" : "only ") + << action_count << " WillOnce()" + << (action_count == 1 ? "" : "s"); + if (repeated_action_specified_) { + ss << " and a WillRepeatedly()"; + } + ss << "."; + Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace". + } +} + +// Implements the .Times() clause. +void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) { + if (last_clause_ == kTimes) { + ExpectSpecProperty(false, + ".Times() cannot appear " + "more than once in an EXPECT_CALL()."); + } else { + ExpectSpecProperty(last_clause_ < kTimes, + ".Times() cannot appear after " + ".InSequence(), .WillOnce(), .WillRepeatedly(), " + "or .RetiresOnSaturation()."); + } + last_clause_ = kTimes; + + SpecifyCardinality(a_cardinality); +} + +// Points to the implicit sequence introduced by a living InSequence +// object (if any) in the current thread or NULL. +GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence; + +// Reports an uninteresting call (whose description is in msg) in the +// manner specified by 'reaction'. +void ReportUninterestingCall(CallReaction reaction, const string& msg) { + // Include a stack trace only if --gmock_verbose=info is specified. + const int stack_frames_to_skip = + GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1; + switch (reaction) { + case kAllow: + Log(kInfo, msg, stack_frames_to_skip); + break; + case kWarn: + Log(kWarning, + msg + + "\nNOTE: You can safely ignore the above warning unless this " + "call should not happen. Do not suppress it by blindly adding " + "an EXPECT_CALL() if you don't mean to enforce the call. " + "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#" + "knowing-when-to-expect for details.\n", + stack_frames_to_skip); + break; + default: // FAIL + Expect(false, NULL, -1, msg); + } +} + +UntypedFunctionMockerBase::UntypedFunctionMockerBase() + : mock_obj_(NULL), name_("") {} + +UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {} + +// Sets the mock object this mock method belongs to, and registers +// this information in the global mock registry. Will be called +// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock +// method. +void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + { + MutexLock l(&g_gmock_mutex); + mock_obj_ = mock_obj; + } + Mock::Register(mock_obj, this); +} + +// Sets the mock object this mock method belongs to, and sets the name +// of the mock function. Will be called upon each invocation of this +// mock function. +void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj, + const char* name) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + // We protect name_ under g_gmock_mutex in case this mock function + // is called from two threads concurrently. + MutexLock l(&g_gmock_mutex); + mock_obj_ = mock_obj; + name_ = name; +} + +// Returns the name of the function being mocked. Must be called +// after RegisterOwner() or SetOwnerAndName() has been called. +const void* UntypedFunctionMockerBase::MockObject() const + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + const void* mock_obj; + { + // We protect mock_obj_ under g_gmock_mutex in case this mock + // function is called from two threads concurrently. + MutexLock l(&g_gmock_mutex); + Assert(mock_obj_ != NULL, __FILE__, __LINE__, + "MockObject() must not be called before RegisterOwner() or " + "SetOwnerAndName() has been called."); + mock_obj = mock_obj_; + } + return mock_obj; +} + +// Returns the name of this mock method. Must be called after +// SetOwnerAndName() has been called. +const char* UntypedFunctionMockerBase::Name() const + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + const char* name; + { + // We protect name_ under g_gmock_mutex in case this mock + // function is called from two threads concurrently. + MutexLock l(&g_gmock_mutex); + Assert(name_ != NULL, __FILE__, __LINE__, + "Name() must not be called before SetOwnerAndName() has " + "been called."); + name = name_; + } + return name; +} + +// Calculates the result of invoking this mock function with the given +// arguments, prints it, and returns it. The caller is responsible +// for deleting the result. +UntypedActionResultHolderBase* +UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + if (untyped_expectations_.size() == 0) { + // No expectation is set on this mock method - we have an + // uninteresting call. + + // We must get Google Mock's reaction on uninteresting calls + // made on this mock object BEFORE performing the action, + // because the action may DELETE the mock object and make the + // following expression meaningless. + const CallReaction reaction = + Mock::GetReactionOnUninterestingCalls(MockObject()); + + // True iff we need to print this call's arguments and return + // value. This definition must be kept in sync with + // the behavior of ReportUninterestingCall(). + const bool need_to_report_uninteresting_call = + // If the user allows this uninteresting call, we print it + // only when he wants informational messages. + reaction == kAllow ? LogIsVisible(kInfo) : + // If the user wants this to be a warning, we print it only + // when he wants to see warnings. + reaction == kWarn ? LogIsVisible(kWarning) : + // Otherwise, the user wants this to be an error, and we + // should always print detailed information in the error. + true; + + if (!need_to_report_uninteresting_call) { + // Perform the action without printing the call information. + return this->UntypedPerformDefaultAction(untyped_args, ""); + } + + // Warns about the uninteresting call. + ::std::stringstream ss; + this->UntypedDescribeUninterestingCall(untyped_args, &ss); + + // Calculates the function result. + UntypedActionResultHolderBase* const result = + this->UntypedPerformDefaultAction(untyped_args, ss.str()); + + // Prints the function result. + if (result != NULL) + result->PrintAsActionResult(&ss); + + ReportUninterestingCall(reaction, ss.str()); + return result; + } + + bool is_excessive = false; + ::std::stringstream ss; + ::std::stringstream why; + ::std::stringstream loc; + const void* untyped_action = NULL; + + // The UntypedFindMatchingExpectation() function acquires and + // releases g_gmock_mutex. + const ExpectationBase* const untyped_expectation = + this->UntypedFindMatchingExpectation( + untyped_args, &untyped_action, &is_excessive, + &ss, &why); + const bool found = untyped_expectation != NULL; + + // True iff we need to print the call's arguments and return value. + // This definition must be kept in sync with the uses of Expect() + // and Log() in this function. + const bool need_to_report_call = + !found || is_excessive || LogIsVisible(kInfo); + if (!need_to_report_call) { + // Perform the action without printing the call information. + return + untyped_action == NULL ? + this->UntypedPerformDefaultAction(untyped_args, "") : + this->UntypedPerformAction(untyped_action, untyped_args); + } + + ss << " Function call: " << Name(); + this->UntypedPrintArgs(untyped_args, &ss); + + // In case the action deletes a piece of the expectation, we + // generate the message beforehand. + if (found && !is_excessive) { + untyped_expectation->DescribeLocationTo(&loc); + } + + UntypedActionResultHolderBase* const result = + untyped_action == NULL ? + this->UntypedPerformDefaultAction(untyped_args, ss.str()) : + this->UntypedPerformAction(untyped_action, untyped_args); + if (result != NULL) + result->PrintAsActionResult(&ss); + ss << "\n" << why.str(); + + if (!found) { + // No expectation matches this call - reports a failure. + Expect(false, NULL, -1, ss.str()); + } else if (is_excessive) { + // We had an upper-bound violation and the failure message is in ss. + Expect(false, untyped_expectation->file(), + untyped_expectation->line(), ss.str()); + } else { + // We had an expected call and the matching expectation is + // described in ss. + Log(kInfo, loc.str() + ss.str(), 2); + } + + return result; +} + +// Returns an Expectation object that references and co-owns exp, +// which must be an expectation on this mock function. +Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { + for (UntypedExpectations::const_iterator it = + untyped_expectations_.begin(); + it != untyped_expectations_.end(); ++it) { + if (it->get() == exp) { + return Expectation(*it); + } + } + + Assert(false, __FILE__, __LINE__, "Cannot find expectation."); + return Expectation(); + // The above statement is just to make the code compile, and will + // never be executed. +} + +// Verifies that all expectations on this mock function have been +// satisfied. Reports one or more Google Test non-fatal failures +// and returns false if not. +bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + g_gmock_mutex.AssertHeld(); + bool expectations_met = true; + for (UntypedExpectations::const_iterator it = + untyped_expectations_.begin(); + it != untyped_expectations_.end(); ++it) { + ExpectationBase* const untyped_expectation = it->get(); + if (untyped_expectation->IsOverSaturated()) { + // There was an upper-bound violation. Since the error was + // already reported when it occurred, there is no need to do + // anything here. + expectations_met = false; + } else if (!untyped_expectation->IsSatisfied()) { + expectations_met = false; + ::std::stringstream ss; + ss << "Actual function call count doesn't match " + << untyped_expectation->source_text() << "...\n"; + // No need to show the source file location of the expectation + // in the description, as the Expect() call that follows already + // takes care of it. + untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); + untyped_expectation->DescribeCallCountTo(&ss); + Expect(false, untyped_expectation->file(), + untyped_expectation->line(), ss.str()); + } + } + + // Deleting our expectations may trigger other mock objects to be deleted, for + // example if an action contains a reference counted smart pointer to that + // mock object, and that is the last reference. So if we delete our + // expectations within the context of the global mutex we may deadlock when + // this method is called again. Instead, make a copy of the set of + // expectations to delete, clear our set within the mutex, and then clear the + // copied set outside of it. + UntypedExpectations expectations_to_delete; + untyped_expectations_.swap(expectations_to_delete); + + g_gmock_mutex.Unlock(); + expectations_to_delete.clear(); + g_gmock_mutex.Lock(); + + return expectations_met; +} + +} // namespace internal + +// Class Mock. + +namespace { + +typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers; + +// The current state of a mock object. Such information is needed for +// detecting leaked mock objects and explicitly verifying a mock's +// expectations. +struct MockObjectState { + MockObjectState() + : first_used_file(NULL), first_used_line(-1), leakable(false) {} + + // Where in the source file an ON_CALL or EXPECT_CALL is first + // invoked on this mock object. + const char* first_used_file; + int first_used_line; + ::std::string first_used_test_case; + ::std::string first_used_test; + bool leakable; // true iff it's OK to leak the object. + FunctionMockers function_mockers; // All registered methods of the object. +}; + +// A global registry holding the state of all mock objects that are +// alive. A mock object is added to this registry the first time +// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It +// is removed from the registry in the mock object's destructor. +class MockObjectRegistry { + public: + // Maps a mock object (identified by its address) to its state. + typedef std::map<const void*, MockObjectState> StateMap; + + // This destructor will be called when a program exits, after all + // tests in it have been run. By then, there should be no mock + // object alive. Therefore we report any living object as test + // failure, unless the user explicitly asked us to ignore it. + ~MockObjectRegistry() { + // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is + // a macro. + + if (!GMOCK_FLAG(catch_leaked_mocks)) + return; + + int leaked_count = 0; + for (StateMap::const_iterator it = states_.begin(); it != states_.end(); + ++it) { + if (it->second.leakable) // The user said it's fine to leak this object. + continue; + + // TODO(wan@google.com): Print the type of the leaked object. + // This can help the user identify the leaked object. + std::cout << "\n"; + const MockObjectState& state = it->second; + std::cout << internal::FormatFileLocation(state.first_used_file, + state.first_used_line); + std::cout << " ERROR: this mock object"; + if (state.first_used_test != "") { + std::cout << " (used in test " << state.first_used_test_case << "." + << state.first_used_test << ")"; + } + std::cout << " should be deleted but never is. Its address is @" + << it->first << "."; + leaked_count++; + } + if (leaked_count > 0) { + std::cout << "\nERROR: " << leaked_count + << " leaked mock " << (leaked_count == 1 ? "object" : "objects") + << " found at program exit.\n"; + std::cout.flush(); + ::std::cerr.flush(); + // RUN_ALL_TESTS() has already returned when this destructor is + // called. Therefore we cannot use the normal Google Test + // failure reporting mechanism. + _exit(1); // We cannot call exit() as it is not reentrant and + // may already have been called. + } + } + + StateMap& states() { return states_; } + + private: + StateMap states_; +}; + +// Protected by g_gmock_mutex. +MockObjectRegistry g_mock_object_registry; + +// Maps a mock object to the reaction Google Mock should have when an +// uninteresting method is called. Protected by g_gmock_mutex. +std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction; + +// Sets the reaction Google Mock should have when an uninteresting +// method of the given mock object is called. +void SetReactionOnUninterestingCalls(const void* mock_obj, + internal::CallReaction reaction) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + internal::MutexLock l(&internal::g_gmock_mutex); + g_uninteresting_call_reaction[mock_obj] = reaction; +} + +} // namespace + +// Tells Google Mock to allow uninteresting calls on the given mock +// object. +void Mock::AllowUninterestingCalls(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + SetReactionOnUninterestingCalls(mock_obj, internal::kAllow); +} + +// Tells Google Mock to warn the user about uninteresting calls on the +// given mock object. +void Mock::WarnUninterestingCalls(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + SetReactionOnUninterestingCalls(mock_obj, internal::kWarn); +} + +// Tells Google Mock to fail uninteresting calls on the given mock +// object. +void Mock::FailUninterestingCalls(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + SetReactionOnUninterestingCalls(mock_obj, internal::kFail); +} + +// Tells Google Mock the given mock object is being destroyed and its +// entry in the call-reaction table should be removed. +void Mock::UnregisterCallReaction(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + internal::MutexLock l(&internal::g_gmock_mutex); + g_uninteresting_call_reaction.erase(mock_obj); +} + +// Returns the reaction Google Mock will have on uninteresting calls +// made on the given mock object. +internal::CallReaction Mock::GetReactionOnUninterestingCalls( + const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + internal::MutexLock l(&internal::g_gmock_mutex); + return (g_uninteresting_call_reaction.count(mock_obj) == 0) ? + internal::kDefault : g_uninteresting_call_reaction[mock_obj]; +} + +// Tells Google Mock to ignore mock_obj when checking for leaked mock +// objects. +void Mock::AllowLeak(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + internal::MutexLock l(&internal::g_gmock_mutex); + g_mock_object_registry.states()[mock_obj].leakable = true; +} + +// Verifies and clears all expectations on the given mock object. If +// the expectations aren't satisfied, generates one or more Google +// Test non-fatal failures and returns false. +bool Mock::VerifyAndClearExpectations(void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + internal::MutexLock l(&internal::g_gmock_mutex); + return VerifyAndClearExpectationsLocked(mock_obj); +} + +// Verifies all expectations on the given mock object and clears its +// default actions and expectations. Returns true iff the +// verification was successful. +bool Mock::VerifyAndClear(void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + internal::MutexLock l(&internal::g_gmock_mutex); + ClearDefaultActionsLocked(mock_obj); + return VerifyAndClearExpectationsLocked(mock_obj); +} + +// Verifies and clears all expectations on the given mock object. If +// the expectations aren't satisfied, generates one or more Google +// Test non-fatal failures and returns false. +bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) + GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { + internal::g_gmock_mutex.AssertHeld(); + if (g_mock_object_registry.states().count(mock_obj) == 0) { + // No EXPECT_CALL() was set on the given mock object. + return true; + } + + // Verifies and clears the expectations on each mock method in the + // given mock object. + bool expectations_met = true; + FunctionMockers& mockers = + g_mock_object_registry.states()[mock_obj].function_mockers; + for (FunctionMockers::const_iterator it = mockers.begin(); + it != mockers.end(); ++it) { + if (!(*it)->VerifyAndClearExpectationsLocked()) { + expectations_met = false; + } + } + + // We don't clear the content of mockers, as they may still be + // needed by ClearDefaultActionsLocked(). + return expectations_met; +} + +// Registers a mock object and a mock method it owns. +void Mock::Register(const void* mock_obj, + internal::UntypedFunctionMockerBase* mocker) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + internal::MutexLock l(&internal::g_gmock_mutex); + g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker); +} + +// Tells Google Mock where in the source code mock_obj is used in an +// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this +// information helps the user identify which object it is. +void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, + const char* file, int line) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + internal::MutexLock l(&internal::g_gmock_mutex); + MockObjectState& state = g_mock_object_registry.states()[mock_obj]; + if (state.first_used_file == NULL) { + state.first_used_file = file; + state.first_used_line = line; + const TestInfo* const test_info = + UnitTest::GetInstance()->current_test_info(); + if (test_info != NULL) { + // TODO(wan@google.com): record the test case name when the + // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or + // TearDownTestCase(). + state.first_used_test_case = test_info->test_case_name(); + state.first_used_test = test_info->name(); + } + } +} + +// Unregisters a mock method; removes the owning mock object from the +// registry when the last mock method associated with it has been +// unregistered. This is called only in the destructor of +// FunctionMockerBase. +void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) + GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { + internal::g_gmock_mutex.AssertHeld(); + for (MockObjectRegistry::StateMap::iterator it = + g_mock_object_registry.states().begin(); + it != g_mock_object_registry.states().end(); ++it) { + FunctionMockers& mockers = it->second.function_mockers; + if (mockers.erase(mocker) > 0) { + // mocker was in mockers and has been just removed. + if (mockers.empty()) { + g_mock_object_registry.states().erase(it); + } + return; + } + } +} + +// Clears all ON_CALL()s set on the given mock object. +void Mock::ClearDefaultActionsLocked(void* mock_obj) + GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { + internal::g_gmock_mutex.AssertHeld(); + + if (g_mock_object_registry.states().count(mock_obj) == 0) { + // No ON_CALL() was set on the given mock object. + return; + } + + // Clears the default actions for each mock method in the given mock + // object. + FunctionMockers& mockers = + g_mock_object_registry.states()[mock_obj].function_mockers; + for (FunctionMockers::const_iterator it = mockers.begin(); + it != mockers.end(); ++it) { + (*it)->ClearDefaultActionsLocked(); + } + + // We don't clear the content of mockers, as they may still be + // needed by VerifyAndClearExpectationsLocked(). +} + +Expectation::Expectation() {} + +Expectation::Expectation( + const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base) + : expectation_base_(an_expectation_base) {} + +Expectation::~Expectation() {} + +// Adds an expectation to a sequence. +void Sequence::AddExpectation(const Expectation& expectation) const { + if (*last_expectation_ != expectation) { + if (last_expectation_->expectation_base() != NULL) { + expectation.expectation_base()->immediate_prerequisites_ + += *last_expectation_; + } + *last_expectation_ = expectation; + } +} + +// Creates the implicit sequence if there isn't one. +InSequence::InSequence() { + if (internal::g_gmock_implicit_sequence.get() == NULL) { + internal::g_gmock_implicit_sequence.set(new Sequence); + sequence_created_ = true; + } else { + sequence_created_ = false; + } +} + +// Deletes the implicit sequence if it was created by the constructor +// of this object. +InSequence::~InSequence() { + if (sequence_created_) { + delete internal::g_gmock_implicit_sequence.get(); + internal::g_gmock_implicit_sequence.set(NULL); + } +} + +} // namespace testing diff --git a/gnu/llvm/utils/unittest/googlemock/src/gmock.cc b/gnu/llvm/utils/unittest/googlemock/src/gmock.cc new file mode 100644 index 00000000000..eac3d842ba0 --- /dev/null +++ b/gnu/llvm/utils/unittest/googlemock/src/gmock.cc @@ -0,0 +1,183 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#include "gmock/gmock.h" +#include "gmock/internal/gmock-port.h" + +namespace testing { + +// TODO(wan@google.com): support using environment variables to +// control the flag values, like what Google Test does. + +GMOCK_DEFINE_bool_(catch_leaked_mocks, true, + "true iff Google Mock should report leaked mock objects " + "as failures."); + +GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity, + "Controls how verbose Google Mock's output is." + " Valid values:\n" + " info - prints all messages.\n" + " warning - prints warnings and errors.\n" + " error - prints errors only."); + +namespace internal { + +// Parses a string as a command line flag. The string should have the +// format "--gmock_flag=value". When def_optional is true, the +// "=value" part can be omitted. +// +// Returns the value of the flag, or NULL if the parsing failed. +static const char* ParseGoogleMockFlagValue(const char* str, + const char* flag, + bool def_optional) { + // str and flag must not be NULL. + if (str == NULL || flag == NULL) return NULL; + + // The flag must start with "--gmock_". + const std::string flag_str = std::string("--gmock_") + flag; + const size_t flag_len = flag_str.length(); + if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; + + // Skips the flag name. + const char* flag_end = str + flag_len; + + // When def_optional is true, it's OK to not have a "=value" part. + if (def_optional && (flag_end[0] == '\0')) { + return flag_end; + } + + // If def_optional is true and there are more characters after the + // flag name, or if def_optional is false, there must be a '=' after + // the flag name. + if (flag_end[0] != '=') return NULL; + + // Returns the string after "=". + return flag_end + 1; +} + +// Parses a string for a Google Mock bool flag, in the form of +// "--gmock_flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +static bool ParseGoogleMockBoolFlag(const char* str, const char* flag, + bool* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseGoogleMockFlagValue(str, flag, true); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Converts the string value to a bool. + *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); + return true; +} + +// Parses a string for a Google Mock string flag, in the form of +// "--gmock_flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +template <typename String> +static bool ParseGoogleMockStringFlag(const char* str, const char* flag, + String* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseGoogleMockFlagValue(str, flag, false); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Sets *value to the value of the flag. + *value = value_str; + return true; +} + +// The internal implementation of InitGoogleMock(). +// +// The type parameter CharType can be instantiated to either char or +// wchar_t. +template <typename CharType> +void InitGoogleMockImpl(int* argc, CharType** argv) { + // Makes sure Google Test is initialized. InitGoogleTest() is + // idempotent, so it's fine if the user has already called it. + InitGoogleTest(argc, argv); + if (*argc <= 0) return; + + for (int i = 1; i != *argc; i++) { + const std::string arg_string = StreamableToString(argv[i]); + const char* const arg = arg_string.c_str(); + + // Do we see a Google Mock flag? + if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks", + &GMOCK_FLAG(catch_leaked_mocks)) || + ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) { + // Yes. Shift the remainder of the argv list left by one. Note + // that argv has (*argc + 1) elements, the last one always being + // NULL. The following loop moves the trailing NULL element as + // well. + for (int j = i; j != *argc; j++) { + argv[j] = argv[j + 1]; + } + + // Decrements the argument count. + (*argc)--; + + // We also need to decrement the iterator as we just removed + // an element. + i--; + } + } +} + +} // namespace internal + +// Initializes Google Mock. This must be called before running the +// tests. In particular, it parses a command line for the flags that +// Google Mock recognizes. Whenever a Google Mock flag is seen, it is +// removed from argv, and *argc is decremented. +// +// No value is returned. Instead, the Google Mock flag variables are +// updated. +// +// Since Google Test is needed for Google Mock to work, this function +// also initializes Google Test and parses its flags, if that hasn't +// been done. +GTEST_API_ void InitGoogleMock(int* argc, char** argv) { + internal::InitGoogleMockImpl(argc, argv); +} + +// This overloaded version can be used in Windows programs compiled in +// UNICODE mode. +GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) { + internal::InitGoogleMockImpl(argc, argv); +} + +} // namespace testing diff --git a/gnu/llvm/utils/unittest/googletest/README.LLVM b/gnu/llvm/utils/unittest/googletest/README.LLVM index afaae9963f3..06c80fea067 100644 --- a/gnu/llvm/utils/unittest/googletest/README.LLVM +++ b/gnu/llvm/utils/unittest/googletest/README.LLVM @@ -1,24 +1,20 @@ LLVM notes ---------- -This directory contains Google Test 1.6.0, with all elements removed except for +This directory contains Google Test 1.8.0, with all elements removed except for the actual source code, to minimize the addition to the LLVM distribution. Cleaned up as follows: # Remove all the unnecessary files and directories -$ rm -f aclocal* CMakeLists.txt configure* Makefile* CHANGES CONTRIBUTORS README -$ rm -rf build-aux cmake codegear fused-src m4 make msvc samples scripts test xcode +$ rm -f CMakeLists.txt configure* Makefile* CHANGES CONTRIBUTORS README README.md .gitignore +$ rm -rf build-aux cmake codegear m4 make msvc samples scripts test xcode docs $ rm -f `find . -name \*\.pump` $ rm -f src/gtest_main.cc # Put the license in the consistent place for LLVM. -$ mv COPYING LICENSE.TXT +$ mv LICENSE LICENSE.TXT Modified as follows: -* Added support for FreeBSD. -* Added support for Minix (PR6797). -* To GTestStreamToHelper in include/gtest/internal/gtest-internal.h, - added the ability to stream with raw_os_ostream. -* To refresh Haiku support in include/gtest/internal/gtest-port.h, - see http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20100621/102898.html +* Added support for Minix and Haiku. +* Added raw_os_ostream support to include/gtest/internal/custom/gtest-printers.h. diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-death-test.h b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-death-test.h index a27883f0a4d..957a69c6a9e 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-death-test.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-death-test.h @@ -51,6 +51,17 @@ GTEST_DECLARE_string_(death_test_style); #if GTEST_HAS_DEATH_TEST +namespace internal { + +// Returns a Boolean value indicating whether the caller is currently +// executing in the context of the death test child process. Tools such as +// Valgrind heap checkers may need this to modify their behavior in death +// tests. IMPORTANT: This is an internal utility. Using it may break the +// implementation of death tests. User code MUST NOT use it. +GTEST_API_ bool InDeathTestChild(); + +} // namespace internal + // The following macros are useful for writing death tests. // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is @@ -75,7 +86,7 @@ GTEST_DECLARE_string_(death_test_style); // for (int i = 0; i < 5; i++) { // EXPECT_DEATH(server.ProcessRequest(i), // "Invalid request .* in ProcessRequest()") -// << "Failed to die on request " << i); +// << "Failed to die on request " << i; // } // // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); @@ -245,10 +256,10 @@ class GTEST_API_ KilledBySignal { # ifdef NDEBUG # define EXPECT_DEBUG_DEATH(statement, regex) \ - do { statement; } while (::testing::internal::AlwaysFalse()) + GTEST_EXECUTE_STATEMENT_(statement, regex) # define ASSERT_DEBUG_DEATH(statement, regex) \ - do { statement; } while (::testing::internal::AlwaysFalse()) + GTEST_EXECUTE_STATEMENT_(statement, regex) # else diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-message.h b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-message.h index 9b7142f3207..47ed669a9b1 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-message.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-message.h @@ -48,8 +48,41 @@ #include <limits> -#include "gtest/internal/gtest-string.h" -#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-port.h" + +#if !GTEST_NO_LLVM_RAW_OSTREAM +#include "llvm/Support/raw_os_ostream.h" + +// LLVM INTERNAL CHANGE: To allow operator<< to work with both +// std::ostreams and LLVM's raw_ostreams, we define a special +// std::ostream with an implicit conversion to raw_ostream& and stream +// to that. This causes the compiler to prefer std::ostream overloads +// but still find raw_ostream& overloads. +namespace llvm { +class convertible_fwd_ostream : public std::ostream { + raw_os_ostream ros_; + +public: + convertible_fwd_ostream(std::ostream& os) + : std::ostream(os.rdbuf()), ros_(*this) {} + operator raw_ostream&() { return ros_; } +}; +} +template <typename T> +inline void GTestStreamToHelper(std::ostream& os, const T& val) { + llvm::convertible_fwd_ostream cos(os); + cos << val; +} +#else +template <typename T> +inline void GTestStreamToHelper(std::ostream& os, const T& val) { + os << val; +} +#endif + +// Ensures that there is at least one operator<< in the global namespace. +// See Message& operator<<(...) below for why. +void operator<<(const testing::internal::Secret&, int); namespace testing { @@ -87,15 +120,7 @@ class GTEST_API_ Message { public: // Constructs an empty Message. - // We allocate the stringstream separately because otherwise each use of - // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's - // stack frame leading to huge stack frames in some cases; gcc does not reuse - // the stack space. - Message() : ss_(new ::std::stringstream) { - // By default, we want there to be enough precision when printing - // a double to a Message. - *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2); - } + Message(); // Copy constructor. Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT @@ -118,7 +143,26 @@ class GTEST_API_ Message { // Streams a non-pointer value to this object. template <typename T> inline Message& operator <<(const T& val) { - ::GTestStreamToHelper(ss_.get(), val); + // Some libraries overload << for STL containers. These + // overloads are defined in the global namespace instead of ::std. + // + // C++'s symbol lookup rule (i.e. Koenig lookup) says that these + // overloads are visible in either the std namespace or the global + // namespace, but not other namespaces, including the testing + // namespace which Google Test's Message class is in. + // + // To allow STL containers (and other types that has a << operator + // defined in the global namespace) to be used in Google Test + // assertions, testing::Message must access the custom << operator + // from the global namespace. With this using declaration, + // overloads of << defined in the global namespace and those + // visible via Koenig lookup are both exposed in this function. +#if GTEST_NO_LLVM_RAW_OSTREAM + using ::operator <<; + *ss_ << val; +#else + ::GTestStreamToHelper(*ss_, val); +#endif return *this; } @@ -140,7 +184,11 @@ class GTEST_API_ Message { if (pointer == NULL) { *ss_ << "(null)"; } else { - ::GTestStreamToHelper(ss_.get(), pointer); +#if GTEST_NO_LLVM_RAW_OSTREAM + *ss_ << pointer; +#else + ::GTestStreamToHelper(*ss_, pointer); +#endif } return *this; } @@ -164,12 +212,8 @@ class GTEST_API_ Message { // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. - Message& operator <<(const wchar_t* wide_c_str) { - return *this << internal::String::ShowWideCString(wide_c_str); - } - Message& operator <<(wchar_t* wide_c_str) { - return *this << internal::String::ShowWideCString(wide_c_str); - } + Message& operator <<(const wchar_t* wide_c_str); + Message& operator <<(wchar_t* wide_c_str); #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 @@ -183,13 +227,11 @@ class GTEST_API_ Message { Message& operator <<(const ::wstring& wstr); #endif // GTEST_HAS_GLOBAL_WSTRING - // Gets the text streamed to this object so far as a String. + // Gets the text streamed to this object so far as an std::string. // Each '\0' character in the buffer is replaced with "\\0". // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - internal::String GetString() const { - return internal::StringStreamToString(ss_.get()); - } + std::string GetString() const; private: @@ -199,16 +241,20 @@ class GTEST_API_ Message { // decide between class template specializations for T and T*, so a // tr1::type_traits-like is_pointer works, and we can overload on that. template <typename T> - inline void StreamHelper(internal::true_type /*dummy*/, T* pointer) { + inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) { if (pointer == NULL) { *ss_ << "(null)"; } else { - ::GTestStreamToHelper(ss_.get(), pointer); + *ss_ << pointer; } } template <typename T> - inline void StreamHelper(internal::false_type /*dummy*/, const T& value) { - ::GTestStreamToHelper(ss_.get(), value); + inline void StreamHelper(internal::false_type /*is_pointer*/, + const T& value) { + // See the comments in Message& operator <<(const T&) above for why + // we need this using statement. + using ::operator <<; + *ss_ << value; } #endif // GTEST_OS_SYMBIAN @@ -225,6 +271,18 @@ inline std::ostream& operator <<(std::ostream& os, const Message& sb) { return os << sb.GetString(); } +namespace internal { + +// Converts a streamable value to an std::string. A NULL pointer is +// converted to "(null)". When the input value is a ::string, +// ::std::string, ::wstring, or ::std::wstring object, each NUL +// character in it is replaced with "\\0". +template <typename T> +std::string StreamableToString(const T& streamable) { + return (Message() << streamable).GetString(); +} + +} // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-param-test.h b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-param-test.h index b1f8bb96102..038f9ba79eb 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-param-test.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-param-test.h @@ -190,6 +190,7 @@ TEST_P(DerivedTest, DoesBlah) { // inside #if GTEST_HAS_PARAM_TEST. #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-param-util-generated.h" #if GTEST_HAS_PARAM_TEST @@ -324,12 +325,6 @@ internal::ParamGenerator<typename Container::value_type> ValuesIn( return ValuesIn(container.begin(), container.end()); } -} // namespace testing - -#include <gtest/internal/gtest-param-util-generated.h> - -namespace testing { - // Values() allows generating tests from explicitly specified list of // parameters. // @@ -1262,7 +1257,7 @@ inline internal::ParamGenerator<bool> Bool() { // Boolean flags: // // class FlagDependentTest -// : public testing::TestWithParam<tuple(bool, bool)> > { +// : public testing::TestWithParam<tuple<bool, bool> > { // virtual void SetUp() { // // Assigns external_flag_1 and external_flag_2 values from the tuple. // tie(external_flag_1, external_flag_2) = GetParam(); @@ -1392,14 +1387,17 @@ internal::CartesianProductHolder10<Generator1, Generator2, Generator3, static int AddToRegistry() { \ ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ GetTestCasePatternHolder<test_case_name>(\ - #test_case_name, __FILE__, __LINE__)->AddTestPattern(\ - #test_case_name, \ - #test_name, \ - new ::testing::internal::TestMetaFactory< \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>()); \ + #test_case_name, \ + ::testing::internal::CodeLocation(\ + __FILE__, __LINE__))->AddTestPattern(\ + #test_case_name, \ + #test_name, \ + new ::testing::internal::TestMetaFactory< \ + GTEST_TEST_CLASS_NAME_(\ + test_case_name, test_name)>()); \ return 0; \ } \ - static int gtest_registering_dummy_; \ + static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ GTEST_DISALLOW_COPY_AND_ASSIGN_(\ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ }; \ @@ -1408,16 +1406,36 @@ internal::CartesianProductHolder10<Generator1, Generator2, Generator3, GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() -# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator) \ +// The optional last argument to INSTANTIATE_TEST_CASE_P allows the user +// to specify a function or functor that generates custom test name suffixes +// based on the test parameters. The function should accept one argument of +// type testing::TestParamInfo<class ParamType>, and return std::string. +// +// testing::PrintToStringParamName is a builtin test suffix generator that +// returns the value of testing::PrintToString(GetParam()). It does not work +// for std::string or C strings. +// +// Note: test names must be non-empty, unique, and may only contain ASCII +// alphanumeric characters or underscore. + +# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator, ...) \ ::testing::internal::ParamGenerator<test_case_name::ParamType> \ gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ - int gtest_##prefix##test_case_name##_dummy_ = \ + ::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \ + const ::testing::TestParamInfo<test_case_name::ParamType>& info) { \ + return ::testing::internal::GetParamNameGen<test_case_name::ParamType> \ + (__VA_ARGS__)(info); \ + } \ + int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ GetTestCasePatternHolder<test_case_name>(\ - #test_case_name, __FILE__, __LINE__)->AddTestCaseInstantiation(\ - #prefix, \ - >est_##prefix##test_case_name##_EvalGenerator_, \ - __FILE__, __LINE__) + #test_case_name, \ + ::testing::internal::CodeLocation(\ + __FILE__, __LINE__))->AddTestCaseInstantiation(\ + #prefix, \ + >est_##prefix##test_case_name##_EvalGenerator_, \ + >est_##prefix##test_case_name##_EvalGenerateName_, \ + __FILE__, __LINE__) } // namespace testing diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-printers.h b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-printers.h index 9cbab3ff4be..8a33164cb38 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-printers.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-printers.h @@ -103,6 +103,10 @@ #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-internal.h" +#if GTEST_HAS_STD_TUPLE_ +# include <tuple> +#endif + namespace testing { // Definitions in the 'internal' and 'internal2' name spaces are @@ -250,6 +254,103 @@ void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { namespace testing { namespace internal { +// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a +// value of type ToPrint that is an operand of a comparison assertion +// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in +// the comparison, and is used to help determine the best way to +// format the value. In particular, when the value is a C string +// (char pointer) and the other operand is an STL string object, we +// want to format the C string as a string, since we know it is +// compared by value with the string object. If the value is a char +// pointer but the other operand is not an STL string object, we don't +// know whether the pointer is supposed to point to a NUL-terminated +// string, and thus want to print it as a pointer to be safe. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + +// The default case. +template <typename ToPrint, typename OtherOperand> +class FormatForComparison { + public: + static ::std::string Format(const ToPrint& value) { + return ::testing::PrintToString(value); + } +}; + +// Array. +template <typename ToPrint, size_t N, typename OtherOperand> +class FormatForComparison<ToPrint[N], OtherOperand> { + public: + static ::std::string Format(const ToPrint* value) { + return FormatForComparison<const ToPrint*, OtherOperand>::Format(value); + } +}; + +// By default, print C string as pointers to be safe, as we don't know +// whether they actually point to a NUL-terminated string. + +#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \ + template <typename OtherOperand> \ + class FormatForComparison<CharType*, OtherOperand> { \ + public: \ + static ::std::string Format(CharType* value) { \ + return ::testing::PrintToString(static_cast<const void*>(value)); \ + } \ + } + +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t); + +#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_ + +// If a C string is compared with an STL string object, we know it's meant +// to point to a NUL-terminated string, and thus can print it as a string. + +#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \ + template <> \ + class FormatForComparison<CharType*, OtherStringType> { \ + public: \ + static ::std::string Format(CharType* value) { \ + return ::testing::PrintToString(value); \ + } \ + } + +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string); + +#if GTEST_HAS_GLOBAL_STRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string); +#endif + +#if GTEST_HAS_GLOBAL_WSTRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring); +#endif + +#if GTEST_HAS_STD_WSTRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring); +#endif + +#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_ + +// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) +// operand to be used in a failure message. The type (but not value) +// of the other operand may affect the format. This allows us to +// print a char* as a raw pointer when it is compared against another +// char* or void*, and print it as a C string when it is compared +// against an std::string object, for example. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +template <typename T1, typename T2> +std::string FormatForComparisonFailureMessage( + const T1& value, const T2& /* other_operand */) { + return FormatForComparison<T1, T2>::Format(value); +} + // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given // value to the given ostream. The caller must ensure that // 'ostream_ptr' is not NULL, or the behavior is undefined. @@ -480,14 +581,16 @@ inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { } #endif // GTEST_HAS_STD_WSTRING -#if GTEST_HAS_TR1_TUPLE -// Overload for ::std::tr1::tuple. Needed for printing function arguments, -// which are packed as tuples. - +#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ // Helper function for printing a tuple. T must be instantiated with // a tuple type. template <typename T> void PrintTupleTo(const T& t, ::std::ostream* os); +#endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ + +#if GTEST_HAS_TR1_TUPLE +// Overload for ::std::tr1::tuple. Needed for printing function arguments, +// which are packed as tuples. // Overloaded PrintTo() for tuples of various arities. We support // tuples of up-to 10 fields. The following implementation works @@ -561,6 +664,13 @@ void PrintTo( } #endif // GTEST_HAS_TR1_TUPLE +#if GTEST_HAS_STD_TUPLE_ +template <typename... Types> +void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} +#endif // GTEST_HAS_STD_TUPLE_ + // Overload for std::pair. template <typename T1, typename T2> void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) { @@ -580,10 +690,7 @@ class UniversalPrinter { public: // MSVC warns about adding const to a function type, so we want to // disable the warning. -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4180) // Temporarily disables warning 4180. -#endif // _MSC_VER + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180) // Note: we deliberately don't call this PrintTo(), as that name // conflicts with ::testing::internal::PrintTo in the body of the @@ -600,9 +707,7 @@ class UniversalPrinter { PrintTo(value, os); } -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif // _MSC_VER + GTEST_DISABLE_MSC_WARNINGS_POP_() }; // UniversalPrintArray(begin, len, os) prints an array of 'len' @@ -630,9 +735,12 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { } } // This overload prints a (const) char array compactly. -GTEST_API_ void UniversalPrintArray(const char* begin, - size_t len, - ::std::ostream* os); +GTEST_API_ void UniversalPrintArray( + const char* begin, size_t len, ::std::ostream* os); + +// This overload prints a (const) wchar_t array compactly. +GTEST_API_ void UniversalPrintArray( + const wchar_t* begin, size_t len, ::std::ostream* os); // Implements printing an array type T[N]. template <typename T, size_t N> @@ -651,10 +759,7 @@ class UniversalPrinter<T&> { public: // MSVC warns about adding const to a function type, so we want to // disable the warning. -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4180) // Temporarily disables warning 4180. -#endif // _MSC_VER + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180) static void Print(const T& value, ::std::ostream* os) { // Prints the address of the value. We use reinterpret_cast here @@ -665,27 +770,78 @@ class UniversalPrinter<T&> { UniversalPrint(value, os); } -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif // _MSC_VER + GTEST_DISABLE_MSC_WARNINGS_POP_() }; // Prints a value tersely: for a reference type, the referenced value // (but not the address) is printed; for a (const) char pointer, the // NUL-terminated string (but not the pointer) is printed. + template <typename T> -void UniversalTersePrint(const T& value, ::std::ostream* os) { - UniversalPrint(value, os); -} -inline void UniversalTersePrint(const char* str, ::std::ostream* os) { - if (str == NULL) { - *os << "NULL"; - } else { - UniversalPrint(string(str), os); +class UniversalTersePrinter { + public: + static void Print(const T& value, ::std::ostream* os) { + UniversalPrint(value, os); } -} -inline void UniversalTersePrint(char* str, ::std::ostream* os) { - UniversalTersePrint(static_cast<const char*>(str), os); +}; +template <typename T> +class UniversalTersePrinter<T&> { + public: + static void Print(const T& value, ::std::ostream* os) { + UniversalPrint(value, os); + } +}; +template <typename T, size_t N> +class UniversalTersePrinter<T[N]> { + public: + static void Print(const T (&value)[N], ::std::ostream* os) { + UniversalPrinter<T[N]>::Print(value, os); + } +}; +template <> +class UniversalTersePrinter<const char*> { + public: + static void Print(const char* str, ::std::ostream* os) { + if (str == NULL) { + *os << "NULL"; + } else { + UniversalPrint(string(str), os); + } + } +}; +template <> +class UniversalTersePrinter<char*> { + public: + static void Print(char* str, ::std::ostream* os) { + UniversalTersePrinter<const char*>::Print(str, os); + } +}; + +#if GTEST_HAS_STD_WSTRING +template <> +class UniversalTersePrinter<const wchar_t*> { + public: + static void Print(const wchar_t* str, ::std::ostream* os) { + if (str == NULL) { + *os << "NULL"; + } else { + UniversalPrint(::std::wstring(str), os); + } + } +}; +#endif + +template <> +class UniversalTersePrinter<wchar_t*> { + public: + static void Print(wchar_t* str, ::std::ostream* os) { + UniversalTersePrinter<const wchar_t*>::Print(str, os); + } +}; + +template <typename T> +void UniversalTersePrint(const T& value, ::std::ostream* os) { + UniversalTersePrinter<T>::Print(value, os); } // Prints a value using the type inferred by the compiler. The @@ -694,19 +850,71 @@ inline void UniversalTersePrint(char* str, ::std::ostream* os) { // NUL-terminated string. template <typename T> void UniversalPrint(const T& value, ::std::ostream* os) { - UniversalPrinter<T>::Print(value, os); + // A workarond for the bug in VC++ 7.1 that prevents us from instantiating + // UniversalPrinter with T directly. + typedef T T1; + UniversalPrinter<T1>::Print(value, os); } -#if GTEST_HAS_TR1_TUPLE typedef ::std::vector<string> Strings; +// TuplePolicy<TupleT> must provide: +// - tuple_size +// size of tuple TupleT. +// - get<size_t I>(const TupleT& t) +// static function extracting element I of tuple TupleT. +// - tuple_element<size_t I>::type +// type of element I of tuple TupleT. +template <typename TupleT> +struct TuplePolicy; + +#if GTEST_HAS_TR1_TUPLE +template <typename TupleT> +struct TuplePolicy { + typedef TupleT Tuple; + static const size_t tuple_size = ::std::tr1::tuple_size<Tuple>::value; + + template <size_t I> + struct tuple_element : ::std::tr1::tuple_element<I, Tuple> {}; + + template <size_t I> + static typename AddReference< + const typename ::std::tr1::tuple_element<I, Tuple>::type>::type get( + const Tuple& tuple) { + return ::std::tr1::get<I>(tuple); + } +}; +template <typename TupleT> +const size_t TuplePolicy<TupleT>::tuple_size; +#endif // GTEST_HAS_TR1_TUPLE + +#if GTEST_HAS_STD_TUPLE_ +template <typename... Types> +struct TuplePolicy< ::std::tuple<Types...> > { + typedef ::std::tuple<Types...> Tuple; + static const size_t tuple_size = ::std::tuple_size<Tuple>::value; + + template <size_t I> + struct tuple_element : ::std::tuple_element<I, Tuple> {}; + + template <size_t I> + static const typename ::std::tuple_element<I, Tuple>::type& get( + const Tuple& tuple) { + return ::std::get<I>(tuple); + } +}; +template <typename... Types> +const size_t TuplePolicy< ::std::tuple<Types...> >::tuple_size; +#endif // GTEST_HAS_STD_TUPLE_ + +#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ // This helper template allows PrintTo() for tuples and // UniversalTersePrintTupleFieldsToStrings() to be defined by // induction on the number of tuple fields. The idea is that // TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N // fields in tuple t, and can be defined in terms of // TuplePrefixPrinter<N - 1>. - +// // The inductive case. template <size_t N> struct TuplePrefixPrinter { @@ -714,9 +922,14 @@ struct TuplePrefixPrinter { template <typename Tuple> static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os); - *os << ", "; - UniversalPrinter<typename ::std::tr1::tuple_element<N - 1, Tuple>::type> - ::Print(::std::tr1::get<N - 1>(t), os); + GTEST_INTENTIONAL_CONST_COND_PUSH_() + if (N > 1) { + GTEST_INTENTIONAL_CONST_COND_POP_() + *os << ", "; + } + UniversalPrinter< + typename TuplePolicy<Tuple>::template tuple_element<N - 1>::type> + ::Print(TuplePolicy<Tuple>::template get<N - 1>(t), os); } // Tersely prints the first N fields of a tuple to a string vector, @@ -725,12 +938,12 @@ struct TuplePrefixPrinter { static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings); ::std::stringstream ss; - UniversalTersePrint(::std::tr1::get<N - 1>(t), &ss); + UniversalTersePrint(TuplePolicy<Tuple>::template get<N - 1>(t), &ss); strings->push_back(ss.str()); } }; -// Base cases. +// Base case. template <> struct TuplePrefixPrinter<0> { template <typename Tuple> @@ -739,34 +952,13 @@ struct TuplePrefixPrinter<0> { template <typename Tuple> static void TersePrintPrefixToStrings(const Tuple&, Strings*) {} }; -// We have to specialize the entire TuplePrefixPrinter<> class -// template here, even though the definition of -// TersePrintPrefixToStrings() is the same as the generic version, as -// Embarcadero (formerly CodeGear, formerly Borland) C++ doesn't -// support specializing a method template of a class template. -template <> -struct TuplePrefixPrinter<1> { - template <typename Tuple> - static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { - UniversalPrinter<typename ::std::tr1::tuple_element<0, Tuple>::type>:: - Print(::std::tr1::get<0>(t), os); - } - template <typename Tuple> - static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { - ::std::stringstream ss; - UniversalTersePrint(::std::tr1::get<0>(t), &ss); - strings->push_back(ss.str()); - } -}; - -// Helper function for printing a tuple. T must be instantiated with -// a tuple type. -template <typename T> -void PrintTupleTo(const T& t, ::std::ostream* os) { +// Helper function for printing a tuple. +// Tuple must be either std::tr1::tuple or std::tuple type. +template <typename Tuple> +void PrintTupleTo(const Tuple& t, ::std::ostream* os) { *os << "("; - TuplePrefixPrinter< ::std::tr1::tuple_size<T>::value>:: - PrintPrefixTo(t, os); + TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::PrintPrefixTo(t, os); *os << ")"; } @@ -776,21 +968,26 @@ void PrintTupleTo(const T& t, ::std::ostream* os) { template <typename Tuple> Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { Strings result; - TuplePrefixPrinter< ::std::tr1::tuple_size<Tuple>::value>:: + TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>:: TersePrintPrefixToStrings(value, &result); return result; } -#endif // GTEST_HAS_TR1_TUPLE +#endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ } // namespace internal template <typename T> ::std::string PrintToString(const T& value) { ::std::stringstream ss; - internal::UniversalTersePrint(value, &ss); + internal::UniversalTersePrinter<T>::Print(value, &ss); return ss.str(); } } // namespace testing +// Include any custom printer added by the local installation. +// We must include this header at the end to make sure it can use the +// declarations from this file. +#include "gtest/internal/custom/gtest-printers.h" + #endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-spi.h b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-spi.h index 736f692e48f..f63fa9a1b2a 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-spi.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-spi.h @@ -68,15 +68,14 @@ class GTEST_API_ ScopedFakeTestPartResultReporter TestPartResultArray* result); // The d'tor restores the previous test part result reporter. - ~ScopedFakeTestPartResultReporter() override; + virtual ~ScopedFakeTestPartResultReporter(); // Appends the TestPartResult object to the TestPartResultArray // received in the constructor. // // This method is from the TestPartResultReporterInterface // interface. - void ReportTestPartResult(const TestPartResult &result) override; - + virtual void ReportTestPartResult(const TestPartResult& result); private: void Init(); @@ -224,7 +223,7 @@ class GTEST_API_ SingleFailureChecker { (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS,\ + ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ >est_failures);\ if (::testing::internal::AlwaysTrue()) { statement; }\ }\ diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-test-part.h b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-test-part.h index d2410c00a3f..77eb844839d 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-test-part.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-test-part.h @@ -62,7 +62,7 @@ class GTEST_API_ TestPartResult { int a_line_number, const char* a_message) : type_(a_type), - file_name_(a_file_name), + file_name_(a_file_name == NULL ? "" : a_file_name), line_number_(a_line_number), summary_(ExtractSummary(a_message)), message_(a_message) { @@ -73,7 +73,9 @@ class GTEST_API_ TestPartResult { // Gets the name of the source file where the test part took place, or // NULL if it's unknown. - const char* file_name() const { return file_name_.c_str(); } + const char* file_name() const { + return file_name_.empty() ? NULL : file_name_.c_str(); + } // Gets the line in the source file where the test part took place, // or -1 if it's unknown. @@ -96,21 +98,22 @@ class GTEST_API_ TestPartResult { // Returns true iff the test part fatally failed. bool fatally_failed() const { return type_ == kFatalFailure; } + private: Type type_; // Gets the summary of the failure message by omitting the stack // trace in it. - static internal::String ExtractSummary(const char* message); + static std::string ExtractSummary(const char* message); // The name of the source file where the test part took place, or - // NULL if the source file is unknown. - internal::String file_name_; + // "" if the source file is unknown. + std::string file_name_; // The line in the source file where the test part took place, or -1 // if the line number is unknown. int line_number_; - internal::String summary_; // The test failure summary. - internal::String message_; // The test failure message. + std::string summary_; // The test failure summary. + std::string message_; // The test failure message. }; // Prints a TestPartResult object. @@ -142,7 +145,7 @@ class GTEST_API_ TestPartResultArray { // This interface knows how to report a test part result. class TestPartResultReporterInterface { public: - virtual ~TestPartResultReporterInterface(); + virtual ~TestPartResultReporterInterface() {} virtual void ReportTestPartResult(const TestPartResult& result) = 0; }; @@ -159,8 +162,8 @@ class GTEST_API_ HasNewFatalFailureHelper : public TestPartResultReporterInterface { public: HasNewFatalFailureHelper(); - ~HasNewFatalFailureHelper() override; - void ReportTestPartResult(const TestPartResult &result) override; + virtual ~HasNewFatalFailureHelper(); + virtual void ReportTestPartResult(const TestPartResult& result); bool has_new_fatal_failure() const { return has_new_fatal_failure_; } private: bool has_new_fatal_failure_; diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-typed-test.h b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-typed-test.h index 6ded1b124b4..5f69d5678ea 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-typed-test.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest-typed-test.h @@ -181,7 +181,8 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); ::testing::internal::TemplateSel< \ GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ GTEST_TYPE_PARAMS_(CaseName)>::Register(\ - "", #CaseName, #TestName, 0); \ + "", ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + #CaseName, #TestName, 0); \ template <typename gtest_TypeParam_> \ void GTEST_TEST_CLASS_NAME_(CaseName, TestName)<gtest_TypeParam_>::TestBody() @@ -236,8 +237,6 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); template <typename gtest_TypeParam_> \ void GTEST_CASE_NAMESPACE_(CaseName)::TestName<gtest_TypeParam_>::TestBody() -// Silencing C99 build warnings -#if 0 # define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ namespace GTEST_CASE_NAMESPACE_(CaseName) { \ typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ @@ -245,7 +244,6 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ __FILE__, __LINE__, #__VA_ARGS__) -#endif // The 'Types' template argument below must have spaces around it // since some compilers may choke on '>>' when passing a template @@ -255,7 +253,10 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); ::testing::internal::TypeParameterizedTestCase<CaseName, \ GTEST_CASE_NAMESPACE_(CaseName)::gtest_AllTests_, \ ::testing::internal::TypeList< Types >::type>::Register(\ - #Prefix, #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) + #Prefix, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + >EST_TYPED_TEST_CASE_P_STATE_(CaseName), \ + #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) #endif // GTEST_HAS_TYPED_TEST_P diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest.h b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest.h index 92ca5cc91c8..f846c5bd669 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest.h @@ -52,6 +52,7 @@ #define GTEST_INCLUDE_GTEST_GTEST_H_ #include <limits> +#include <ostream> #include <vector> #include "gtest/internal/gtest-internal.h" @@ -69,14 +70,14 @@ // class ::string, which has the same interface as ::std::string, but // has a different implementation. // -// The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that +// You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that // ::string is available AND is a distinct type to ::std::string, or // define it to 0 to indicate otherwise. // -// If the user's ::std::string and ::string are the same class due to -// aliasing, they should define GTEST_HAS_GLOBAL_STRING to 0. +// If ::std::string and ::string are the same class on your platform +// due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0. // -// If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined +// If you do not define GTEST_HAS_GLOBAL_STRING, it is defined // heuristically. namespace testing { @@ -153,25 +154,15 @@ class ExecDeathTest; class NoExecDeathTest; class FinalSuccessChecker; class GTestFlagSaver; +class StreamingListenerTest; class TestResultAccessor; class TestEventListenersAccessor; class TestEventRepeater; +class UnitTestRecordPropertyTestHelper; class WindowsDeathTest; class UnitTestImpl* GetUnitTestImpl(); void ReportFailureInUnknownLocation(TestPartResult::Type result_type, - const String& message); - -// Converts a streamable value to a String. A NULL pointer is -// converted to "(null)". When the input value is a ::string, -// ::std::string, ::wstring, or ::std::wstring object, each NUL -// character in it is replaced with "\\0". -// Declared in gtest-internal.h but defined here, so that it has access -// to the definition of the Message class, required by the ARM -// compiler. -template <typename T> -String StreamableToString(const T& streamable) { - return (Message() << streamable).GetString(); -} + const std::string& message); } // namespace internal @@ -267,8 +258,31 @@ class GTEST_API_ AssertionResult { // Copy constructor. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult(const AssertionResult& other); + + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */) + // Used in the EXPECT_TRUE/FALSE(bool_expression). - explicit AssertionResult(bool success) : success_(success) {} + // + // T must be contextually convertible to bool. + // + // The second parameter prevents this overload from being considered if + // the argument is implicitly convertible to AssertionResult. In that case + // we want AssertionResult's copy constructor to be used. + template <typename T> + explicit AssertionResult( + const T& success, + typename internal::EnableIf< + !internal::ImplicitlyConvertible<T, AssertionResult>::value>::type* + /*enabler*/ = NULL) + : success_(success) {} + + GTEST_DISABLE_MSC_WARNINGS_POP_() + + // Assignment operator. + AssertionResult& operator=(AssertionResult other) { + swap(other); + return *this; + } // Returns true iff the assertion succeeded. operator bool() const { return success_; } // NOLINT @@ -309,6 +323,9 @@ class GTEST_API_ AssertionResult { message_->append(a_message.GetString().c_str()); } + // Swap the contents of this AssertionResult with other. + void swap(AssertionResult& other); + // Stores result of the assertion predicate. bool success_; // Stores the message describing the condition in case the expectation @@ -316,8 +333,6 @@ class GTEST_API_ AssertionResult { // Referenced via a pointer to avoid taking too much stack frame space // with test assertions. internal::scoped_ptr< ::std::string> message_; - - GTEST_DISALLOW_ASSIGN_(AssertionResult); }; // Makes a successful assertion result. @@ -344,8 +359,8 @@ GTEST_API_ AssertionResult AssertionFailure(const Message& msg); // // class FooTest : public testing::Test { // protected: -// virtual void SetUp() { ... } -// virtual void TearDown() { ... } +// void SetUp() override { ... } +// void TearDown() override { ... } // ... // }; // @@ -391,20 +406,21 @@ class GTEST_API_ Test { // non-fatal) failure. static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } - // Logs a property for the current test. Only the last value for a given - // key is remembered. - // These are public static so they can be called from utility functions - // that are not members of the test fixture. - // The arguments are const char* instead strings, as Google Test is used - // on platforms where string doesn't compile. - // - // Note that a driving consideration for these RecordProperty methods - // was to produce xml output suited to the Greenspan charting utility, - // which at present will only chart values that fit in a 32-bit int. It - // is the user's responsibility to restrict their values to 32-bit ints - // if they intend them to be used with Greenspan. - static void RecordProperty(const char* key, const char* value); - static void RecordProperty(const char* key, int value); + // Logs a property for the current test, test case, or for the entire + // invocation of the test program when used outside of the context of a + // test case. Only the last value for a given key is remembered. These + // are public static so they can be called from utility functions that are + // not members of the test fixture. Calls to RecordProperty made during + // lifespan of the test (from the moment its constructor starts to the + // moment its destructor finishes) will be output in XML as attributes of + // the <testcase> element. Properties recorded from fixture's + // SetUpTestCase or TearDownTestCase are logged as attributes of the + // corresponding <testsuite> element. Calls to RecordProperty made in the + // global context (before or after invocation of RUN_ALL_TESTS and from + // SetUp/TearDown method of Environment objects registered with Google + // Test) will be output as attributes of the <testsuites> element. + static void RecordProperty(const std::string& key, const std::string& value); + static void RecordProperty(const std::string& key, int value); protected: // Creates a Test object. @@ -436,20 +452,19 @@ class GTEST_API_ Test { // internal method to avoid clashing with names used in user TESTs. void DeleteSelf_() { delete this; } - // Uses a GTestFlagSaver to save and restore all Google Test flags. - const internal::GTestFlagSaver* const gtest_flag_saver_; + const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_; - // Often a user mis-spells SetUp() as Setup() and spends a long time + // Often a user misspells SetUp() as Setup() and spends a long time // wondering why it is never called by Google Test. The declaration of // the following method is solely for catching such an error at // compile time: // // - The return type is deliberately chosen to be not void, so it - // will be a conflict if a user declares void Setup() in his test - // fixture. + // will be a conflict if void Setup() is declared in the user's + // test fixture. // // - This method is private, so it will be another compiler error - // if a user calls it from his test fixture. + // if the method is called from the user's test fixture. // // DO NOT OVERRIDE THIS FUNCTION. // @@ -473,7 +488,7 @@ class TestProperty { // C'tor. TestProperty does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestProperty object. - TestProperty(const char* a_key, const char* a_value) : + TestProperty(const std::string& a_key, const std::string& a_value) : key_(a_key), value_(a_value) { } @@ -488,15 +503,15 @@ class TestProperty { } // Sets a new value, overriding the one supplied in the constructor. - void SetValue(const char* new_value) { + void SetValue(const std::string& new_value) { value_ = new_value; } private: // The key supplied by the user. - internal::String key_; + std::string key_; // The value supplied by the user. - internal::String value_; + std::string value_; }; // The result of a single Test. This includes a list of @@ -547,6 +562,7 @@ class GTEST_API_ TestResult { private: friend class TestInfo; + friend class TestCase; friend class UnitTest; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::ExecDeathTest; @@ -571,13 +587,16 @@ class GTEST_API_ TestResult { // a non-fatal failure if invalid (e.g., if it conflicts with reserved // key names). If a property is already recorded for the same key, the // value will be updated, rather than storing multiple values for the same - // key. - void RecordProperty(const TestProperty& test_property); + // key. xml_element specifies the element for which the property is being + // recorded and is used for validation. + void RecordProperty(const std::string& xml_element, + const TestProperty& test_property); // Adds a failure if the key is a reserved attribute of Google Test // testcase tags. Returns true if the property is valid. // TODO(russr): Validate attribute names are legal and human readable. - static bool ValidateTestProperty(const TestProperty& test_property); + static bool ValidateTestProperty(const std::string& xml_element, + const TestProperty& test_property); // Adds a test part result to the list. void AddTestPartResult(const TestPartResult& test_part_result); @@ -650,9 +669,15 @@ class GTEST_API_ TestInfo { return NULL; } - // Returns true if this test should run, that is if the test is not disabled - // (or it is disabled but the also_run_disabled_tests flag has been specified) - // and its full name matches the user-specified filter. + // Returns the file name where this test is defined. + const char* file() const { return location_.file.c_str(); } + + // Returns the line where this test is defined. + int line() const { return location_.line; } + + // Returns true if this test should run, that is if the test is not + // disabled (or it is disabled but the also_run_disabled_tests flag has + // been specified) and its full name matches the user-specified filter. // // Google Test allows the user to filter the tests by their full names. // The full name of a test Bar in test case Foo is defined as @@ -668,21 +693,31 @@ class GTEST_API_ TestInfo { // contains the character 'A' or starts with "Foo.". bool should_run() const { return should_run_; } + // Returns true iff this test will appear in the XML report. + bool is_reportable() const { + // For now, the XML report includes all tests matching the filter. + // In the future, we may trim tests that are excluded because of + // sharding. + return matches_filter_; + } + // Returns the result of the test. const TestResult* result() const { return &result_; } private: - #if GTEST_HAS_DEATH_TEST friend class internal::DefaultDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST friend class Test; friend class TestCase; friend class internal::UnitTestImpl; + friend class internal::StreamingListenerTest; friend TestInfo* internal::MakeAndRegisterTestInfo( - const char* test_case_name, const char* name, + const char* test_case_name, + const char* name, const char* type_param, const char* value_param, + internal::CodeLocation code_location, internal::TypeId fixture_class_id, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, @@ -690,9 +725,11 @@ class GTEST_API_ TestInfo { // Constructs a TestInfo object. The newly constructed instance assumes // ownership of the factory object. - TestInfo(const char* test_case_name, const char* name, - const char* a_type_param, - const char* a_value_param, + TestInfo(const std::string& test_case_name, + const std::string& name, + const char* a_type_param, // NULL if not a type-parameterized test + const char* a_value_param, // NULL if not a value-parameterized test + internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory); @@ -719,6 +756,7 @@ class GTEST_API_ TestInfo { // Text representation of the value parameter, or NULL if this is not a // value-parameterized test. const internal::scoped_ptr<const ::std::string> value_param_; + internal::CodeLocation location_; const internal::TypeId fixture_class_id_; // ID of the test fixture class bool should_run_; // True iff this test should run bool is_disabled_; // True iff this test is disabled @@ -778,9 +816,15 @@ class GTEST_API_ TestCase { // Gets the number of failed tests in this test case. int failed_test_count() const; + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + // Gets the number of disabled tests in this test case. int disabled_test_count() const; + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + // Get the number of tests in this test case that should run. int test_to_run_count() const; @@ -800,6 +844,10 @@ class GTEST_API_ TestCase { // total_test_count() - 1. If i is not in that range, returns NULL. const TestInfo* GetTestInfo(int i) const; + // Returns the TestResult that holds test properties recorded during + // execution of SetUpTestCase and TearDownTestCase. + const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; } + private: friend class Test; friend class internal::UnitTestImpl; @@ -852,11 +900,22 @@ class GTEST_API_ TestCase { return test_info->should_run() && test_info->result()->Failed(); } + // Returns true iff the test is disabled and will be reported in the XML + // report. + static bool TestReportableDisabled(const TestInfo* test_info) { + return test_info->is_reportable() && test_info->is_disabled_; + } + // Returns true iff test is disabled. static bool TestDisabled(const TestInfo* test_info) { return test_info->is_disabled_; } + // Returns true iff this test will appear in the XML report. + static bool TestReportable(const TestInfo* test_info) { + return test_info->is_reportable(); + } + // Returns true if the given test should run. static bool ShouldRunTest(const TestInfo* test_info) { return test_info->should_run(); @@ -869,7 +928,7 @@ class GTEST_API_ TestCase { void UnshuffleTests(); // Name of the test case. - internal::String name_; + std::string name_; // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. const internal::scoped_ptr<const ::std::string> type_param_; @@ -888,13 +947,16 @@ class GTEST_API_ TestCase { bool should_run_; // Elapsed time, in milliseconds. TimeInMillis elapsed_time_; + // Holds test properties recorded during execution of SetUpTestCase and + // TearDownTestCase. + TestResult ad_hoc_test_result_; // We disallow copying TestCases. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); }; // An Environment object is capable of setting up and tearing down an -// environment. The user should subclass this to define his own +// environment. You should subclass this to define your own // environment(s). // // An Environment object does the set-up and tear-down in virtual @@ -910,7 +972,7 @@ class GTEST_API_ TestCase { class Environment { public: // The d'tor is virtual as we need to subclass Environment. - virtual ~Environment(); + virtual ~Environment() {} // Override this to define how to set up the environment. virtual void SetUp() {} @@ -928,7 +990,7 @@ class Environment { // the order the corresponding events are fired. class TestEventListener { public: - virtual ~TestEventListener(); + virtual ~TestEventListener() {} // Fired before any test activity starts. virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; @@ -980,24 +1042,22 @@ class TestEventListener { // comments about each method please see the definition of TestEventListener // above. class EmptyTestEventListener : public TestEventListener { - virtual void anchor(); public: - void OnTestProgramStart(const UnitTest & /*unit_test*/) override {} - void OnTestIterationStart(const UnitTest & /*unit_test*/, - int /*iteration*/) override {} - void OnEnvironmentsSetUpStart(const UnitTest & /*unit_test*/) override {} - void OnEnvironmentsSetUpEnd(const UnitTest & /*unit_test*/) override {} - void OnTestCaseStart(const TestCase & /*test_case*/) override {} - void OnTestStart(const TestInfo & /*test_info*/) override {} - void OnTestPartResult(const TestPartResult & /*test_part_result*/) override { - } - void OnTestEnd(const TestInfo & /*test_info*/) override {} - void OnTestCaseEnd(const TestCase & /*test_case*/) override {} - void OnEnvironmentsTearDownStart(const UnitTest & /*unit_test*/) override {} - void OnEnvironmentsTearDownEnd(const UnitTest & /*unit_test*/) override {} - void OnTestIterationEnd(const UnitTest & /*unit_test*/, - int /*iteration*/) override {} - void OnTestProgramEnd(const UnitTest & /*unit_test*/) override {} + virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, + int /*iteration*/) {} + virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} + virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} + virtual void OnTestStart(const TestInfo& /*test_info*/) {} + virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} + virtual void OnTestEnd(const TestInfo& /*test_info*/) {} + virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} + virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} + virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, + int /*iteration*/) {} + virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} }; // TestEventListeners lets users add listeners to track events in Google Test. @@ -1109,11 +1169,13 @@ class GTEST_API_ UnitTest { // Returns the TestCase object for the test that's currently running, // or NULL if no test is running. - const TestCase* current_test_case() const; + const TestCase* current_test_case() const + GTEST_LOCK_EXCLUDED_(mutex_); // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. - const TestInfo* current_test_info() const; + const TestInfo* current_test_info() const + GTEST_LOCK_EXCLUDED_(mutex_); // Returns the random seed used at the start of the current test run. int random_seed() const; @@ -1123,7 +1185,8 @@ class GTEST_API_ UnitTest { // value-parameterized tests and instantiate and register them. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - internal::ParameterizedTestCaseRegistry& parameterized_test_registry(); + internal::ParameterizedTestCaseRegistry& parameterized_test_registry() + GTEST_LOCK_EXCLUDED_(mutex_); #endif // GTEST_HAS_PARAM_TEST // Gets the number of successful test cases. @@ -1145,15 +1208,25 @@ class GTEST_API_ UnitTest { // Gets the number of failed tests. int failed_test_count() const; + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + // Gets the number of disabled tests. int disabled_test_count() const; + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + // Gets the number of all tests. int total_test_count() const; // Gets the number of tests that should run. int test_to_run_count() const; + // Gets the time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp() const; + // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const; @@ -1168,6 +1241,10 @@ class GTEST_API_ UnitTest { // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* GetTestCase(int i) const; + // Returns the TestResult containing information on test failures and + // properties logged outside of individual test cases. + const TestResult& ad_hoc_test_result() const; + // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& listeners(); @@ -1191,12 +1268,16 @@ class GTEST_API_ UnitTest { void AddTestPartResult(TestPartResult::Type result_type, const char* file_name, int line_number, - const internal::String& message, - const internal::String& os_stack_trace); + const std::string& message, + const std::string& os_stack_trace) + GTEST_LOCK_EXCLUDED_(mutex_); - // Adds a TestProperty to the current TestResult object. If the result already - // contains a property with the same key, the value will be updated. - void RecordPropertyForCurrentTest(const char* key, const char* value); + // Adds a TestProperty to the current TestResult object when invoked from + // inside a test, to current TestCase's ad_hoc_test_result_ when invoked + // from SetUpTestCase or TearDownTestCase, or to the global property set + // when invoked elsewhere. If the result already contains a property with + // the same key, the value will be updated. + void RecordProperty(const std::string& key, const std::string& value); // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. @@ -1211,11 +1292,13 @@ class GTEST_API_ UnitTest { friend class Test; friend class internal::AssertHelper; friend class internal::ScopedTrace; + friend class internal::StreamingListenerTest; + friend class internal::UnitTestRecordPropertyTestHelper; friend Environment* AddGlobalTestEnvironment(Environment* env); friend internal::UnitTestImpl* internal::GetUnitTestImpl(); friend void internal::ReportFailureInUnknownLocation( TestPartResult::Type result_type, - const internal::String& message); + const std::string& message); // Creates an empty UnitTest. UnitTest(); @@ -1225,10 +1308,12 @@ class GTEST_API_ UnitTest { // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. - void PushGTestTrace(const internal::TraceInfo& trace); + void PushGTestTrace(const internal::TraceInfo& trace) + GTEST_LOCK_EXCLUDED_(mutex_); // Pops a trace from the per-thread Google Test trace stack. - void PopGTestTrace(); + void PopGTestTrace() + GTEST_LOCK_EXCLUDED_(mutex_); // Protects mutable state in *impl_. This is mutable as some const // methods need to lock it too. @@ -1283,62 +1368,42 @@ GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); namespace internal { -// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) -// operand to be used in a failure message. The type (but not value) -// of the other operand may affect the format. This allows us to -// print a char* as a raw pointer when it is compared against another -// char*, and print it as a C string when it is compared against an -// std::string object, for example. -// -// The default implementation ignores the type of the other operand. -// Some specialized versions are used to handle formatting wide or -// narrow C strings. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +// Separate the error generating code from the code path to reduce the stack +// frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers +// when calling EXPECT_* in a tight loop. template <typename T1, typename T2> -String FormatForComparisonFailureMessage(const T1& value, - const T2& /* other_operand */) { - // C++Builder compiles this incorrectly if the namespace isn't explicitly - // given. - return ::testing::PrintToString(value); +AssertionResult CmpHelperEQFailure(const char* lhs_expression, + const char* rhs_expression, + const T1& lhs, const T2& rhs) { + return EqFailure(lhs_expression, + rhs_expression, + FormatForComparisonFailureMessage(lhs, rhs), + FormatForComparisonFailureMessage(rhs, lhs), + false); } // The helper function for {ASSERT|EXPECT}_EQ. template <typename T1, typename T2> -AssertionResult CmpHelperEQ(const char* expected_expression, - const char* actual_expression, - const T1& expected, - const T2& actual) { -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4389) // Temporarily disables warning on - // signed/unsigned mismatch. -#pragma warning(disable:4805) // Temporarily disables warning on - // unsafe mix of types -#endif - - if (expected == actual) { +AssertionResult CmpHelperEQ(const char* lhs_expression, + const char* rhs_expression, + const T1& lhs, + const T2& rhs) { +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4389 /* signed/unsigned mismatch */) + if (lhs == rhs) { return AssertionSuccess(); } +GTEST_DISABLE_MSC_WARNINGS_POP_() -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif - - return EqFailure(expected_expression, - actual_expression, - FormatForComparisonFailureMessage(expected, actual), - FormatForComparisonFailureMessage(actual, expected), - false); + return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs); } // With this overloaded version, we allow anonymous enums to be used // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums // can be implicitly cast to BiggestInt. -GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression, - const char* actual_expression, - BiggestInt expected, - BiggestInt actual); +GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression, + const char* rhs_expression, + BiggestInt lhs, + BiggestInt rhs); // The helper class for {ASSERT|EXPECT}_EQ. The template argument // lhs_is_null_literal is true iff the first argument to ASSERT_EQ() @@ -1349,12 +1414,11 @@ class EqHelper { public: // This templatized version is for the general case. template <typename T1, typename T2> - static AssertionResult Compare(const char* expected_expression, - const char* actual_expression, - const T1& expected, - const T2& actual) { - return CmpHelperEQ(expected_expression, actual_expression, expected, - actual); + static AssertionResult Compare(const char* lhs_expression, + const char* rhs_expression, + const T1& lhs, + const T2& rhs) { + return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } // With this overloaded version, we allow anonymous enums to be used @@ -1363,12 +1427,11 @@ class EqHelper { // // Even though its body looks the same as the above version, we // cannot merge the two, as it will make anonymous enums unhappy. - static AssertionResult Compare(const char* expected_expression, - const char* actual_expression, - BiggestInt expected, - BiggestInt actual) { - return CmpHelperEQ(expected_expression, actual_expression, expected, - actual); + static AssertionResult Compare(const char* lhs_expression, + const char* rhs_expression, + BiggestInt lhs, + BiggestInt rhs) { + return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } }; @@ -1383,40 +1446,52 @@ class EqHelper<true> { // EXPECT_EQ(false, a_bool). template <typename T1, typename T2> static AssertionResult Compare( - const char* expected_expression, - const char* actual_expression, - const T1& expected, - const T2& actual, + const char* lhs_expression, + const char* rhs_expression, + const T1& lhs, + const T2& rhs, // The following line prevents this overload from being considered if T2 // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) // expands to Compare("", "", NULL, my_ptr), which requires a conversion // to match the Secret* in the other overload, which would otherwise make // this template match better. typename EnableIf<!is_pointer<T2>::value>::type* = 0) { - return CmpHelperEQ(expected_expression, actual_expression, expected, - actual); + return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } // This version will be picked when the second argument to ASSERT_EQ() is a // pointer, e.g. ASSERT_EQ(NULL, a_pointer). template <typename T> static AssertionResult Compare( - const char* expected_expression, - const char* actual_expression, + const char* lhs_expression, + const char* rhs_expression, // We used to have a second template parameter instead of Secret*. That // template parameter would deduce to 'long', making this a better match // than the first overload even without the first overload's EnableIf. // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to // non-pointer argument" (even a deduced integral argument), so the old // implementation caused warnings in user code. - Secret* /* expected (NULL) */, - T* actual) { - // We already know that 'expected' is a null pointer. - return CmpHelperEQ(expected_expression, actual_expression, - static_cast<T*>(NULL), actual); + Secret* /* lhs (NULL) */, + T* rhs) { + // We already know that 'lhs' is a null pointer. + return CmpHelperEQ(lhs_expression, rhs_expression, + static_cast<T*>(NULL), rhs); } }; +// Separate the error generating code from the code path to reduce the stack +// frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers +// when calling EXPECT_OP in a tight loop. +template <typename T1, typename T2> +AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, + const T1& val1, const T2& val2, + const char* op) { + return AssertionFailure() + << "Expected: (" << expr1 << ") " << op << " (" << expr2 + << "), actual: " << FormatForComparisonFailureMessage(val1, val2) + << " vs " << FormatForComparisonFailureMessage(val2, val1); +} + // A macro for implementing the helper functions needed to implement // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste // of similar code. @@ -1427,6 +1502,7 @@ class EqHelper<true> { // with gcc 4. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ template <typename T1, typename T2>\ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ @@ -1434,10 +1510,7 @@ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ - return AssertionFailure() \ - << "Expected: (" << expr1 << ") " #op " (" << expr2\ - << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ - << " vs " << FormatForComparisonFailureMessage(val2, val1);\ + return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\ }\ }\ GTEST_API_ AssertionResult CmpHelper##op_name(\ @@ -1450,29 +1523,29 @@ GTEST_IMPL_CMP_HELPER_(NE, !=); // Implements the helper function for {ASSERT|EXPECT}_LE GTEST_IMPL_CMP_HELPER_(LE, <=); // Implements the helper function for {ASSERT|EXPECT}_LT -GTEST_IMPL_CMP_HELPER_(LT, < ); +GTEST_IMPL_CMP_HELPER_(LT, <); // Implements the helper function for {ASSERT|EXPECT}_GE GTEST_IMPL_CMP_HELPER_(GE, >=); // Implements the helper function for {ASSERT|EXPECT}_GT -GTEST_IMPL_CMP_HELPER_(GT, > ); +GTEST_IMPL_CMP_HELPER_(GT, >); #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual); +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASEEQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual); +GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); // The helper function for {ASSERT|EXPECT}_STRNE. // @@ -1494,10 +1567,10 @@ GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, // Helper function for *_STREQ on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const wchar_t* expected, - const wchar_t* actual); +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, + const char* s2_expression, + const wchar_t* s1, + const wchar_t* s2); // Helper function for *_STRNE on wide strings. // @@ -1555,28 +1628,28 @@ namespace internal { // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template <typename RawType> -AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression, - const char* actual_expression, - RawType expected, - RawType actual) { - const FloatingPoint<RawType> lhs(expected), rhs(actual); +AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, + const char* rhs_expression, + RawType lhs_value, + RawType rhs_value) { + const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value); if (lhs.AlmostEquals(rhs)) { return AssertionSuccess(); } - ::std::stringstream expected_ss; - expected_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) - << expected; + ::std::stringstream lhs_ss; + lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) + << lhs_value; - ::std::stringstream actual_ss; - actual_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) - << actual; + ::std::stringstream rhs_ss; + rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) + << rhs_value; - return EqFailure(expected_expression, - actual_expression, - StringStreamToString(&expected_ss), - StringStreamToString(&actual_ss), + return EqFailure(lhs_expression, + rhs_expression, + StringStreamToString(&lhs_ss), + StringStreamToString(&rhs_ss), false); } @@ -1618,9 +1691,9 @@ class GTEST_API_ AssertHelper { : type(t), file(srcfile), line(line_num), message(msg) { } TestPartResult::Type const type; - const char* const file; - int const line; - String const message; + const char* const file; + int const line; + std::string const message; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); @@ -1679,7 +1752,12 @@ class WithParamInterface { // references static data, to reduce the opportunity for incorrect uses // like writing 'WithParamInterface<bool>::GetParam()' for a test that // uses a fixture whose parameter type is int. - const ParamType& GetParam() const { return *parameter_; } + const ParamType& GetParam() const { + GTEST_CHECK_(parameter_ != NULL) + << "GetParam() can only be called inside a value-parameterized test " + << "-- did you intend to write TEST_P instead of TEST_F?"; + return *parameter_; + } private: // Sets parameter value. The caller is responsible for making sure the value @@ -1725,12 +1803,6 @@ class TestWithParam : public Test, public WithParamInterface<T> { // usually want the fail-fast behavior of FAIL and ASSERT_*, but those // writing data-driven tests often find themselves using ADD_FAILURE // and EXPECT_* more. -// -// Examples: -// -// EXPECT_TRUE(server.StatusIsOK()); -// ASSERT_FALSE(server.HasPendingRequest(port)) -// << "There are still pending requests " << "on port " << port; // Generates a nonfatal failure with a generic message. #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") @@ -1785,13 +1857,13 @@ class TestWithParam : public Test, public WithParamInterface<T> { // AssertionResult. For more information on how to use AssertionResult with // these macros see comments on that class. #define EXPECT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ + GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \ GTEST_NONFATAL_FAILURE_) #define EXPECT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_NONFATAL_FAILURE_) #define ASSERT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ + GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \ GTEST_FATAL_FAILURE_) #define ASSERT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ @@ -1803,12 +1875,12 @@ class TestWithParam : public Test, public WithParamInterface<T> { // Macros for testing equalities and inequalities. // -// * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual -// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 -// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 -// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 -// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 -// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 +// * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2 +// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 +// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 +// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 +// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 +// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 // // When they are not, Google Test prints both the tested expressions and // their actual values. The values must be compatible built-in types, @@ -1830,8 +1902,8 @@ class TestWithParam : public Test, public WithParamInterface<T> { // are related, not how their content is related. To compare two C // strings by content, use {ASSERT|EXPECT}_STR*(). // -// 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to -// {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you +// 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to +// {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you // what the actual value is when it fails, and similarly for the // other comparisons. // @@ -1847,12 +1919,12 @@ class TestWithParam : public Test, public WithParamInterface<T> { // ASSERT_LT(i, array_size); // ASSERT_GT(records.size(), 0) << "There is no record left."; -#define EXPECT_EQ(expected, actual) \ +#define EXPECT_EQ(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal:: \ - EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \ - expected, actual) -#define EXPECT_NE(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual) + EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \ + val1, val2) +#define EXPECT_NE(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) #define EXPECT_LE(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) #define EXPECT_LT(val1, val2) \ @@ -1862,10 +1934,10 @@ class TestWithParam : public Test, public WithParamInterface<T> { #define EXPECT_GT(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) -#define GTEST_ASSERT_EQ(expected, actual) \ +#define GTEST_ASSERT_EQ(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal:: \ - EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \ - expected, actual) + EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \ + val1, val2) #define GTEST_ASSERT_NE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) #define GTEST_ASSERT_LE(val1, val2) \ @@ -1904,7 +1976,7 @@ class TestWithParam : public Test, public WithParamInterface<T> { # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) #endif -// C String Comparisons. All tests treat NULL and any non-NULL string +// C-string Comparisons. All tests treat NULL and any non-NULL string // as different. Two NULLs are equal. // // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 @@ -1920,29 +1992,29 @@ class TestWithParam : public Test, public WithParamInterface<T> { // // These macros evaluate their arguments exactly once. -#define EXPECT_STREQ(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) +#define EXPECT_STREQ(s1, s2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) #define EXPECT_STRNE(s1, s2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) -#define EXPECT_STRCASEEQ(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) +#define EXPECT_STRCASEEQ(s1, s2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) #define EXPECT_STRCASENE(s1, s2)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) -#define ASSERT_STREQ(expected, actual) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) +#define ASSERT_STREQ(s1, s2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) #define ASSERT_STRNE(s1, s2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) -#define ASSERT_STRCASEEQ(expected, actual) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) +#define ASSERT_STRCASEEQ(s1, s2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) #define ASSERT_STRCASENE(s1, s2)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) // Macros for comparing floating-point numbers. // -// * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual): +// * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2): // Tests that two float values are almost equal. -// * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual): +// * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2): // Tests that two double values are almost equal. // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): // Tests that v1 and v2 are within the given distance to each other. @@ -1952,21 +2024,21 @@ class TestWithParam : public Test, public WithParamInterface<T> { // FloatingPoint template class in gtest-internal.h if you are // interested in the implementation details. -#define EXPECT_FLOAT_EQ(expected, actual)\ +#define EXPECT_FLOAT_EQ(val1, val2)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ - expected, actual) + val1, val2) -#define EXPECT_DOUBLE_EQ(expected, actual)\ +#define EXPECT_DOUBLE_EQ(val1, val2)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ - expected, actual) + val1, val2) -#define ASSERT_FLOAT_EQ(expected, actual)\ +#define ASSERT_FLOAT_EQ(val1, val2)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ - expected, actual) + val1, val2) -#define ASSERT_DOUBLE_EQ(expected, actual)\ +#define ASSERT_DOUBLE_EQ(val1, val2)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ - expected, actual) + val1, val2) #define EXPECT_NEAR(val1, val2, abs_error)\ EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ @@ -2088,8 +2160,8 @@ bool StaticAssertTypeEq() { // The convention is to end the test case name with "Test". For // example, a test case for the Foo class can be named FooTest. // -// The user should put his test code between braces after using this -// macro. Example: +// Test code should appear between braces after an invocation of +// this macro. Example: // // TEST(FooTest, InitializesCorrectly) { // Foo foo; @@ -2145,15 +2217,20 @@ bool StaticAssertTypeEq() { GTEST_TEST_(test_fixture, test_name, test_fixture, \ ::testing::internal::GetTypeId<test_fixture>()) -// Use this macro in main() to run all tests. It returns 0 if all +} // namespace testing + +// Use this function in main() to run all tests. It returns 0 if all // tests are successful, or 1 otherwise. // // RUN_ALL_TESTS() should be invoked after the command line has been // parsed by InitGoogleTest(). +// +// This function was formerly a macro; thus, it is in the global +// namespace and has an all-caps name. +int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; -#define RUN_ALL_TESTS()\ - (::testing::UnitTest::GetInstance()->Run()) - -} // namespace testing +inline int RUN_ALL_TESTS() { + return ::testing::UnitTest::GetInstance()->Run(); +} #endif // GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest_pred_impl.h b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest_pred_impl.h index 3805f85bdb3..30ae712f50e 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/gtest_pred_impl.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/gtest_pred_impl.h @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// This file is AUTOMATICALLY GENERATED on 09/24/2010 by command +// This file is AUTOMATICALLY GENERATED on 10/31/2011 by command // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // // Implements a family of generic predicate assertion macros. @@ -98,7 +98,7 @@ AssertionResult AssertPred1Helper(const char* pred_text, // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. // Don't use this in your code. #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, v1),\ + GTEST_ASSERT_(pred_format(#v1, v1), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use @@ -144,7 +144,7 @@ AssertionResult AssertPred2Helper(const char* pred_text, // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. // Don't use this in your code. #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2),\ + GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use @@ -197,7 +197,7 @@ AssertionResult AssertPred3Helper(const char* pred_text, // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. // Don't use this in your code. #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3),\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use @@ -257,7 +257,7 @@ AssertionResult AssertPred4Helper(const char* pred_text, // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. // Don't use this in your code. #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4),\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use @@ -324,7 +324,7 @@ AssertionResult AssertPred5Helper(const char* pred_text, // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. // Don't use this in your code. #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5),\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/custom/gtest-port.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/custom/gtest-port.h new file mode 100644 index 00000000000..7e744bd3bb3 --- /dev/null +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/custom/gtest-port.h @@ -0,0 +1,69 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Injection point for custom user configurations. +// The following macros can be defined: +// +// Flag related macros: +// GTEST_FLAG(flag_name) +// GTEST_USE_OWN_FLAGFILE_FLAG_ - Define to 0 when the system provides its +// own flagfile flag parsing. +// GTEST_DECLARE_bool_(name) +// GTEST_DECLARE_int32_(name) +// GTEST_DECLARE_string_(name) +// GTEST_DEFINE_bool_(name, default_val, doc) +// GTEST_DEFINE_int32_(name, default_val, doc) +// GTEST_DEFINE_string_(name, default_val, doc) +// +// Test filtering: +// GTEST_TEST_FILTER_ENV_VAR_ - The name of an environment variable that +// will be used if --GTEST_FLAG(test_filter) +// is not provided. +// +// Logging: +// GTEST_LOG_(severity) +// GTEST_CHECK_(condition) +// Functions LogToStderr() and FlushInfoLog() have to be provided too. +// +// Threading: +// GTEST_HAS_NOTIFICATION_ - Enabled if Notification is already provided. +// GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Enabled if Mutex and ThreadLocal are +// already provided. +// Must also provide GTEST_DECLARE_STATIC_MUTEX_(mutex) and +// GTEST_DEFINE_STATIC_MUTEX_(mutex) +// +// GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) +// GTEST_LOCK_EXCLUDED_(locks) +// +// ** Custom implementation starts here ** + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/custom/gtest-printers.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/custom/gtest-printers.h new file mode 100644 index 00000000000..60c1ea050b6 --- /dev/null +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/custom/gtest-printers.h @@ -0,0 +1,42 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// This file provides an injection point for custom printers in a local +// installation of gTest. +// It will be included from gtest-printers.h and the overrides in this file +// will be visible to everyone. +// See documentation at gtest/gtest-printers.h for details on how to define a +// custom printer. +// +// ** Custom implementation starts here ** + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/custom/gtest.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/custom/gtest.h new file mode 100644 index 00000000000..c27412a8981 --- /dev/null +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/custom/gtest.h @@ -0,0 +1,41 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Injection point for custom user configurations. +// The following macros can be defined: +// +// GTEST_OS_STACK_TRACE_GETTER_ - The name of an implementation of +// OsStackTraceGetterInterface. +// +// ** Custom implementation starts here ** + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-death-test-internal.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-death-test-internal.h index 04c676ce5ff..01b5d5ebc90 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -79,7 +79,7 @@ class GTEST_API_ DeathTest { static bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test); DeathTest(); - virtual ~DeathTest(); + virtual ~DeathTest() { } // A helper class that aborts a death test when it's deleted. class ReturnSentinel { @@ -127,11 +127,11 @@ class GTEST_API_ DeathTest { // the last death test. static const char* LastMessage(); - static void set_last_death_test_message(const String& message); + static void set_last_death_test_message(const std::string& message); private: // A string containing a description of the outcome of the last death test. - static String last_death_test_message_; + static std::string last_death_test_message_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); }; @@ -139,7 +139,7 @@ class GTEST_API_ DeathTest { // Factory interface for death tests. May be mocked out for testing. class DeathTestFactory { public: - virtual ~DeathTestFactory(); + virtual ~DeathTestFactory() { } virtual bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) = 0; }; @@ -147,8 +147,8 @@ class DeathTestFactory { // A concrete DeathTestFactory implementation for normal use. class DefaultDeathTestFactory : public DeathTestFactory { public: - bool Create(const char *statement, const RE *regex, const char *file, - int line, DeathTest **test) override; + virtual bool Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test); }; // Returns true if exit_status describes a process that was terminated @@ -215,12 +215,23 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status); // The symbol "fail" here expands to something into which a message // can be streamed. +// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in +// NDEBUG mode. In this case we need the statements to be executed, the regex is +// ignored, and the macro must accept a streamed message even though the message +// is never printed. +# define GTEST_EXECUTE_STATEMENT_(statement, regex) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } else \ + ::testing::Message() + // A class representing the parsed contents of the // --gtest_internal_run_death_test flag, as it existed when // RUN_ALL_TESTS was called. class InternalRunDeathTestFlag { public: - InternalRunDeathTestFlag(const String& a_file, + InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index, int a_write_fd) @@ -232,13 +243,13 @@ class InternalRunDeathTestFlag { posix::Close(write_fd_); } - String file() const { return file_; } + const std::string& file() const { return file_; } int line() const { return line_; } int index() const { return index_; } int write_fd() const { return write_fd_; } private: - String file_; + std::string file_; int line_; int index_; int write_fd_; diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-filepath.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-filepath.h index 823c6bdc258..7a13b4b0de6 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-filepath.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-filepath.h @@ -61,11 +61,7 @@ class GTEST_API_ FilePath { FilePath() : pathname_("") { } FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } - explicit FilePath(const char* pathname) : pathname_(pathname) { - Normalize(); - } - - explicit FilePath(const String& pathname) : pathname_(pathname) { + explicit FilePath(const std::string& pathname) : pathname_(pathname) { Normalize(); } @@ -78,7 +74,7 @@ class GTEST_API_ FilePath { pathname_ = rhs.pathname_; } - String ToString() const { return pathname_; } + const std::string& string() const { return pathname_; } const char* c_str() const { return pathname_.c_str(); } // Returns the current working directory, or "" if unsuccessful. @@ -111,8 +107,8 @@ class GTEST_API_ FilePath { const FilePath& base_name, const char* extension); - // Returns true iff the path is NULL or "". - bool IsEmpty() const { return c_str() == NULL || *c_str() == '\0'; } + // Returns true iff the path is "". + bool IsEmpty() const { return pathname_.empty(); } // If input name has a trailing separator character, removes it and returns // the name, otherwise return the name string unmodified. @@ -196,12 +192,12 @@ class GTEST_API_ FilePath { void Normalize(); - // Returns a pointer to the last occurrence of a valid path separator in + // Returns a pointer to the last occurence of a valid path separator in // the FilePath. On Windows, for example, both '/' and '\' are valid path // separators. Returns NULL if no path separator was found. const char* FindLastPathSeparator() const; - String pathname_; + std::string pathname_; }; // class FilePath } // namespace internal diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-internal.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-internal.h index 3c7eee81b1d..ebd1cf615de 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-internal.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-internal.h @@ -46,20 +46,25 @@ # include <unistd.h> #endif // GTEST_OS_LINUX +#if GTEST_HAS_EXCEPTIONS +# include <stdexcept> +#endif + #include <ctype.h> +#include <float.h> #include <string.h> #include <iomanip> #include <limits> +#include <map> #include <set> +#include <string> +#include <vector> +#include "gtest/gtest-message.h" #include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-type-util.h" -#if !GTEST_NO_LLVM_RAW_OSTREAM -#include "llvm/Support/raw_os_ostream.h" -#endif - // Due to C++ preprocessor weirdness, we need double indirection to // concatenate two tokens when one of them is __LINE__. Writing // @@ -71,61 +76,6 @@ #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar -// Google Test defines the testing::Message class to allow construction of -// test messages via the << operator. The idea is that anything -// streamable to std::ostream can be streamed to a testing::Message. -// This allows a user to use his own types in Google Test assertions by -// overloading the << operator. -// -// util/gtl/stl_logging-inl.h overloads << for STL containers. These -// overloads cannot be defined in the std namespace, as that will be -// undefined behavior. Therefore, they are defined in the global -// namespace instead. -// -// C++'s symbol lookup rule (i.e. Koenig lookup) says that these -// overloads are visible in either the std namespace or the global -// namespace, but not other namespaces, including the testing -// namespace which Google Test's Message class is in. -// -// To allow STL containers (and other types that has a << operator -// defined in the global namespace) to be used in Google Test assertions, -// testing::Message must access the custom << operator from the global -// namespace. Hence this helper function. -// -// Note: Jeffrey Yasskin suggested an alternative fix by "using -// ::operator<<;" in the definition of Message's operator<<. That fix -// doesn't require a helper function, but unfortunately doesn't -// compile with MSVC. - -// LLVM INTERNAL CHANGE: To allow operator<< to work with both -// std::ostreams and LLVM's raw_ostreams, we define a special -// std::ostream with an implicit conversion to raw_ostream& and stream -// to that. This causes the compiler to prefer std::ostream overloads -// but still find raw_ostream& overloads. -#if !GTEST_NO_LLVM_RAW_OSTREAM -namespace llvm { -class convertible_fwd_ostream : public std::ostream { - virtual void anchor(); - raw_os_ostream ros_; - -public: - convertible_fwd_ostream(std::ostream& os) - : std::ostream(os.rdbuf()), ros_(*this) {} - operator raw_ostream&() { return ros_; } -}; -} -template <typename T> -inline void GTestStreamToHelper(std::ostream* os, const T& val) { - llvm::convertible_fwd_ostream cos(*os); - cos << val; -} -#else -template <typename T> -inline void GTestStreamToHelper(std::ostream* os, const T& val) { - *os << val; -} -#endif - class ProtocolMessage; namespace proto2 { class Message; } @@ -150,18 +100,10 @@ class ScopedTrace; // Implements scoped trace. class TestInfoImpl; // Opaque implementation of TestInfo class UnitTestImpl; // Opaque implementation of UnitTest -// How many times InitGoogleTest() has been called. -extern int g_init_gtest_count; - // The text used in failure messages to indicate the start of the // stack trace. GTEST_API_ extern const char kStackTraceMarker[]; -// A secret type that Google Test users don't know about. It has no -// definition on purpose. Therefore it's impossible to create a -// Secret object, which is what we want. -class Secret; - // Two overloaded helpers for checking at compile time whether an // expression is a null pointer literal (i.e. NULL or any 0-valued // compile-time integral constant). Their return values have @@ -192,8 +134,23 @@ char (&IsNullLiteralHelper(...))[2]; // NOLINT #endif // GTEST_ELLIPSIS_NEEDS_POD_ // Appends the user-supplied message to the Google-Test-generated message. -GTEST_API_ String AppendUserMessage(const String& gtest_msg, - const Message& user_msg); +GTEST_API_ std::string AppendUserMessage( + const std::string& gtest_msg, const Message& user_msg); + +#if GTEST_HAS_EXCEPTIONS + +// This exception is thrown by (and only by) a failed Google Test +// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions +// are enabled). We derive it from std::runtime_error, which is for +// errors presumably detectable only at run time. Since +// std::runtime_error inherits from std::exception, many testing +// frameworks know how to extract and print the message inside it. +class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error { + public: + explicit GoogleTestFailureException(const TestPartResult& failure); +}; + +#endif // GTEST_HAS_EXCEPTIONS // A helper class for creating scoped traces in user programs. class GTEST_API_ ScopedTrace { @@ -214,76 +171,35 @@ class GTEST_API_ ScopedTrace { // c'tor and d'tor. Therefore it doesn't // need to be used otherwise. -// Converts a streamable value to a String. A NULL pointer is -// converted to "(null)". When the input value is a ::string, -// ::std::string, ::wstring, or ::std::wstring object, each NUL -// character in it is replaced with "\\0". -// Declared here but defined in gtest.h, so that it has access -// to the definition of the Message class, required by the ARM -// compiler. -template <typename T> -String StreamableToString(const T& streamable); - -// The Symbian compiler has a bug that prevents it from selecting the -// correct overload of FormatForComparisonFailureMessage (see below) -// unless we pass the first argument by reference. If we do that, -// however, Visual Age C++ 10.1 generates a compiler error. Therefore -// we only apply the work-around for Symbian. -#if defined(__SYMBIAN32__) -# define GTEST_CREF_WORKAROUND_ const& -#else -# define GTEST_CREF_WORKAROUND_ -#endif - -// When this operand is a const char* or char*, if the other operand -// is a ::std::string or ::string, we print this operand as a C string -// rather than a pointer (we do the same for wide strings); otherwise -// we print it as a pointer to be safe. - -// This internal macro is used to avoid duplicated code. -#define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\ -inline String FormatForComparisonFailureMessage(\ - operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \ - const operand2_type& /*operand2*/) {\ - return operand1_printer(str);\ -}\ -inline String FormatForComparisonFailureMessage(\ - const operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \ - const operand2_type& /*operand2*/) {\ - return operand1_printer(str);\ -} - -GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted) -#if GTEST_HAS_STD_WSTRING -GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted) -#endif // GTEST_HAS_STD_WSTRING - -#if GTEST_HAS_GLOBAL_STRING -GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted) -#endif // GTEST_HAS_GLOBAL_STRING -#if GTEST_HAS_GLOBAL_WSTRING -GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted) -#endif // GTEST_HAS_GLOBAL_WSTRING - -#undef GTEST_FORMAT_IMPL_ - -// The next four overloads handle the case where the operand being -// printed is a char/wchar_t pointer and the other operand is not a -// string/wstring object. In such cases, we just print the operand as -// a pointer to be safe. -#define GTEST_FORMAT_CHAR_PTR_IMPL_(CharType) \ - template <typename T> \ - String FormatForComparisonFailureMessage(CharType* GTEST_CREF_WORKAROUND_ p, \ - const T&) { \ - return PrintToString(static_cast<const void*>(p)); \ - } - -GTEST_FORMAT_CHAR_PTR_IMPL_(char) -GTEST_FORMAT_CHAR_PTR_IMPL_(const char) -GTEST_FORMAT_CHAR_PTR_IMPL_(wchar_t) -GTEST_FORMAT_CHAR_PTR_IMPL_(const wchar_t) - -#undef GTEST_FORMAT_CHAR_PTR_IMPL_ +namespace edit_distance { +// Returns the optimal edits to go from 'left' to 'right'. +// All edits cost the same, with replace having lower priority than +// add/remove. +// Simple implementation of the Wagner–Fischer algorithm. +// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm +enum EditType { kMatch, kAdd, kRemove, kReplace }; +GTEST_API_ std::vector<EditType> CalculateOptimalEdits( + const std::vector<size_t>& left, const std::vector<size_t>& right); + +// Same as above, but the input is represented as strings. +GTEST_API_ std::vector<EditType> CalculateOptimalEdits( + const std::vector<std::string>& left, + const std::vector<std::string>& right); + +// Create a diff of the input strings in Unified diff format. +GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left, + const std::vector<std::string>& right, + size_t context = 2); + +} // namespace edit_distance + +// Calculate the diff between 'left' and 'right' and return it in unified diff +// format. +// If not null, stores in 'total_line_count' the total number of lines found +// in left + right. +GTEST_API_ std::string DiffStrings(const std::string& left, + const std::string& right, + size_t* total_line_count); // Constructs and returns the message for an equality assertion // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. @@ -302,12 +218,12 @@ GTEST_FORMAT_CHAR_PTR_IMPL_(const wchar_t) // be inserted into the message. GTEST_API_ AssertionResult EqFailure(const char* expected_expression, const char* actual_expression, - const String& expected_value, - const String& actual_value, + const std::string& expected_value, + const std::string& actual_value, bool ignoring_case); // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. -GTEST_API_ String GetBoolAssertionFailureMessage( +GTEST_API_ std::string GetBoolAssertionFailureMessage( const AssertionResult& assertion_result, const char* expression_text, const char* actual_predicate_value, @@ -382,7 +298,7 @@ class FloatingPoint { // bits. Therefore, 4 should be enough for ordinary use. // // See the following article for more details on ULP: - // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm. + // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ static const size_t kMaxUlps = 4; // Constructs a FloatingPoint from a raw floating-point number. @@ -409,6 +325,9 @@ class FloatingPoint { return ReinterpretBits(kExponentBitMask); } + // Returns the maximum representable finite floating-point number. + static RawType Max(); + // Non-static methods // Returns the bits that represents this number. @@ -489,6 +408,13 @@ class FloatingPoint { FloatingPointUnion u_; }; +// We cannot use std::numeric_limits<T>::max() as it clashes with the max() +// macro defined by <windows.h>. +template <> +inline float FloatingPoint<float>::Max() { return FLT_MAX; } +template <> +inline double FloatingPoint<double>::Max() { return DBL_MAX; } + // Typedefs the instances of the FloatingPoint template class that we // care to use. typedef FloatingPoint<float> Float; @@ -537,7 +463,7 @@ GTEST_API_ TypeId GetTestTypeId(); // of a Test object. class TestFactoryBase { public: - virtual ~TestFactoryBase(); + virtual ~TestFactoryBase() {} // Creates a test instance to run. The instance is both created and destroyed // within TestInfoImpl::Run() @@ -555,7 +481,7 @@ class TestFactoryBase { template <class TestClass> class TestFactoryImpl : public TestFactoryBase { public: - Test *CreateTest() override { return new TestClass; } + virtual Test* CreateTest() { return new TestClass; } }; #if GTEST_OS_WINDOWS @@ -575,6 +501,13 @@ GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, typedef void (*SetUpTestCaseFunc)(); typedef void (*TearDownTestCaseFunc)(); +struct CodeLocation { + CodeLocation(const string& a_file, int a_line) : file(a_file), line(a_line) {} + + string file; + int line; +}; + // Creates a new TestInfo object and registers it with Google Test; // returns the created object. // @@ -583,9 +516,10 @@ typedef void (*TearDownTestCaseFunc)(); // test_case_name: name of the test case // name: name of the test // type_param the name of the test's type parameter, or NULL if -// this is not a typed or a type-parameterized test. +// this is not a typed or a type-parameterized test. // value_param text representation of the test's value parameter, // or NULL if this is not a type-parameterized test. +// code_location: code location where the test is defined // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case @@ -593,9 +527,11 @@ typedef void (*TearDownTestCaseFunc)(); // The newly created TestInfo instance will assume // ownership of the factory object. GTEST_API_ TestInfo* MakeAndRegisterTestInfo( - const char* test_case_name, const char* name, + const char* test_case_name, + const char* name, const char* type_param, const char* value_param, + CodeLocation code_location, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, @@ -625,10 +561,21 @@ class GTEST_API_ TypedTestCasePState { fflush(stderr); posix::Abort(); } - defined_test_names_.insert(test_name); + registered_tests_.insert( + ::std::make_pair(test_name, CodeLocation(file, line))); return true; } + bool TestExists(const std::string& test_name) const { + return registered_tests_.count(test_name) > 0; + } + + const CodeLocation& GetCodeLocation(const std::string& test_name) const { + RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name); + GTEST_CHECK_(it != registered_tests_.end()); + return it->second; + } + // Verifies that registered_tests match the test names in // defined_test_names_; returns registered_tests if successful, or // aborts the program otherwise. @@ -636,8 +583,10 @@ class GTEST_API_ TypedTestCasePState { const char* file, int line, const char* registered_tests); private: + typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap; + bool registered_; - ::std::set<const char*> defined_test_names_; + RegisteredTestsMap registered_tests_; }; // Skips to the first non-space char after the first comma in 'str'; @@ -653,11 +602,16 @@ inline const char* SkipComma(const char* str) { // Returns the prefix of 'str' before the first comma in it; returns // the entire string if it contains no comma. -inline String GetPrefixUntilComma(const char* str) { +inline std::string GetPrefixUntilComma(const char* str) { const char* comma = strchr(str, ','); - return comma == NULL ? String(str) : String(str, comma - str); + return comma == NULL ? str : std::string(str, comma); } +// Splits a given string on a given delimiter, populating a given +// vector with the fields. +void SplitString(const ::std::string& str, char delimiter, + ::std::vector< ::std::string>* dest); + // TypeParameterizedTest<Fixture, TestSel, Types>::Register() // registers a list of type-parameterized tests with Google Test. The // return value is insignificant - we just need to return something @@ -672,8 +626,10 @@ class TypeParameterizedTest { // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, // Types). Valid values for 'index' are [0, N - 1] where N is the // length of Types. - static bool Register(const char* prefix, const char* case_name, - const char* test_names, int index) { + static bool Register(const char* prefix, + CodeLocation code_location, + const char* case_name, const char* test_names, + int index) { typedef typename Types::Head Type; typedef Fixture<Type> FixtureClass; typedef typename GTEST_BIND_(TestSel, Type) TestClass; @@ -681,11 +637,12 @@ class TypeParameterizedTest { // First, registers the first type-parameterized test in the type // list. MakeAndRegisterTestInfo( - String::Format("%s%s%s/%d", prefix, prefix[0] == '\0' ? "" : "/", - case_name, index).c_str(), - GetPrefixUntilComma(test_names).c_str(), + (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + "/" + + StreamableToString(index)).c_str(), + StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), GetTypeName<Type>().c_str(), NULL, // No value parameter. + code_location, GetTypeId<FixtureClass>(), TestClass::SetUpTestCase, TestClass::TearDownTestCase, @@ -693,7 +650,7 @@ class TypeParameterizedTest { // Next, recurses (at compile time) with the tail of the type list. return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail> - ::Register(prefix, case_name, test_names, index + 1); + ::Register(prefix, code_location, case_name, test_names, index + 1); } }; @@ -701,8 +658,9 @@ class TypeParameterizedTest { template <GTEST_TEMPLATE_ Fixture, class TestSel> class TypeParameterizedTest<Fixture, TestSel, Types0> { public: - static bool Register(const char* /*prefix*/, const char* /*case_name*/, - const char* /*test_names*/, int /*index*/) { + static bool Register(const char* /*prefix*/, CodeLocation, + const char* /*case_name*/, const char* /*test_names*/, + int /*index*/) { return true; } }; @@ -714,17 +672,31 @@ class TypeParameterizedTest<Fixture, TestSel, Types0> { template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types> class TypeParameterizedTestCase { public: - static bool Register(const char* prefix, const char* case_name, - const char* test_names) { + static bool Register(const char* prefix, CodeLocation code_location, + const TypedTestCasePState* state, + const char* case_name, const char* test_names) { + std::string test_name = StripTrailingSpaces( + GetPrefixUntilComma(test_names)); + if (!state->TestExists(test_name)) { + fprintf(stderr, "Failed to get code location for test %s.%s at %s.", + case_name, test_name.c_str(), + FormatFileLocation(code_location.file.c_str(), + code_location.line).c_str()); + fflush(stderr); + posix::Abort(); + } + const CodeLocation& test_location = state->GetCodeLocation(test_name); + typedef typename Tests::Head Head; // First, register the first test in 'Test' for each type in 'Types'. TypeParameterizedTest<Fixture, Head, Types>::Register( - prefix, case_name, test_names, 0); + prefix, test_location, case_name, test_names, 0); // Next, recurses (at compile time) with the tail of the test list. return TypeParameterizedTestCase<Fixture, typename Tests::Tail, Types> - ::Register(prefix, case_name, SkipComma(test_names)); + ::Register(prefix, code_location, state, + case_name, SkipComma(test_names)); } }; @@ -732,15 +704,16 @@ class TypeParameterizedTestCase { template <GTEST_TEMPLATE_ Fixture, typename Types> class TypeParameterizedTestCase<Fixture, Templates0, Types> { public: - static bool Register(const char* /*prefix*/, const char* /*case_name*/, - const char* /*test_names*/) { + static bool Register(const char* /*prefix*/, CodeLocation, + const TypedTestCasePState* /*state*/, + const char* /*case_name*/, const char* /*test_names*/) { return true; } }; #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P -// Returns the current OS stack trace as a String. +// Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter @@ -750,8 +723,8 @@ class TypeParameterizedTestCase<Fixture, Templates0, Types> { // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -GTEST_API_ String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, - int skip_count); +GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( + UnitTest* unit_test, int skip_count); // Helpers for suppressing warnings on unreachable code or constant // condition. @@ -826,13 +799,19 @@ struct RemoveConst<const T> { typedef T type; }; // NOLINT // MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above // definition to fail to remove the const in 'const int[3]' and 'const // char[3][4]'. The following specialization works around the bug. -// However, it causes trouble with GCC and thus needs to be -// conditionally compiled. -#if defined(_MSC_VER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) template <typename T, size_t N> struct RemoveConst<const T[N]> { typedef typename RemoveConst<T>::type type[N]; }; + +#if defined(_MSC_VER) && _MSC_VER < 1400 +// This is the only specialization that allows VC++ 7.1 to remove const in +// 'const int[3] and 'const int[3][4]'. However, it causes trouble with GCC +// and thus needs to be conditionally compiled. +template <typename T, size_t N> +struct RemoveConst<T[N]> { + typedef typename RemoveConst<T>::type type[N]; +}; #endif // A handy wrapper around RemoveConst that works when the argument @@ -881,7 +860,7 @@ class ImplicitlyConvertible { // MakeFrom() is an expression whose type is From. We cannot simply // use From(), as the type From may not have a public default // constructor. - static From MakeFrom(); + static typename AddReference<From>::type MakeFrom(); // These two functions are overloaded. Given an expression // Helper(x), the compiler will pick the first version if x can be @@ -899,25 +878,20 @@ class ImplicitlyConvertible { // We have to put the 'public' section after the 'private' section, // or MSVC refuses to compile the code. public: - // MSVC warns about implicitly converting from double to int for - // possible loss of data, so we need to temporarily disable the - // warning. -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4244) // Temporarily disables warning 4244. - - static const bool value = - sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; -# pragma warning(pop) // Restores the warning state. -#elif defined(__BORLANDC__) +#if defined(__BORLANDC__) // C++Builder cannot use member overload resolution during template // instantiation. The simplest workaround is to use its C++0x type traits // functions (C++Builder 2009 and above only). static const bool value = __is_convertible(From, To); #else + // MSVC warns about implicitly converting from double to int for + // possible loss of data, so we need to temporarily disable the + // warning. + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244) static const bool value = sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; -#endif // _MSV_VER + GTEST_DISABLE_MSC_WARNINGS_POP_() +#endif // __BORLANDC__ }; template <typename From, typename To> const bool ImplicitlyConvertible<From, To>::value; @@ -1043,11 +1017,10 @@ void CopyArray(const T* from, size_t size, U* to) { // The relation between an NativeArray object (see below) and the // native array it represents. -enum RelationToSource { - kReference, // The NativeArray references the native array. - kCopy // The NativeArray makes a copy of the native array and - // owns the copy. -}; +// We use 2 different structs to allow non-copyable types to be used, as long +// as RelationToSourceReference() is passed. +struct RelationToSourceReference {}; +struct RelationToSourceCopy {}; // Adapts a native array to a read-only STL-style container. Instead // of the complete STL container concept, this adaptor only implements @@ -1065,22 +1038,23 @@ class NativeArray { typedef Element* iterator; typedef const Element* const_iterator; - // Constructs from a native array. - NativeArray(const Element* array, size_t count, RelationToSource relation) { - Init(array, count, relation); + // Constructs from a native array. References the source. + NativeArray(const Element* array, size_t count, RelationToSourceReference) { + InitRef(array, count); + } + + // Constructs from a native array. Copies the source. + NativeArray(const Element* array, size_t count, RelationToSourceCopy) { + InitCopy(array, count); } // Copy constructor. NativeArray(const NativeArray& rhs) { - Init(rhs.array_, rhs.size_, rhs.relation_to_source_); + (this->*rhs.clone_)(rhs.array_, rhs.size_); } ~NativeArray() { - // Ensures that the user doesn't instantiate NativeArray with a - // const or reference type. - static_cast<void>(StaticAssertTypeEqHelper<Element, - GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>()); - if (relation_to_source_ == kCopy) + if (clone_ != &NativeArray::InitRef) delete[] array_; } @@ -1094,23 +1068,30 @@ class NativeArray { } private: - // Initializes this object; makes a copy of the input array if - // 'relation' is kCopy. - void Init(const Element* array, size_t a_size, RelationToSource relation) { - if (relation == kReference) { - array_ = array; - } else { - Element* const copy = new Element[a_size]; - CopyArray(array, a_size, copy); - array_ = copy; - } + enum { + kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper< + Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value, + }; + + // Initializes this object with a copy of the input. + void InitCopy(const Element* array, size_t a_size) { + Element* const copy = new Element[a_size]; + CopyArray(array, a_size, copy); + array_ = copy; size_ = a_size; - relation_to_source_ = relation; + clone_ = &NativeArray::InitCopy; + } + + // Initializes this object with a reference of the input. + void InitRef(const Element* array, size_t a_size) { + array_ = array; + size_ = a_size; + clone_ = &NativeArray::InitRef; } const Element* array_; size_t size_; - RelationToSource relation_to_source_; + void (NativeArray::*clone_)(const Element*, size_t); GTEST_DISALLOW_ASSIGN_(NativeArray); }; @@ -1245,6 +1226,7 @@ class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ ::test_info_ =\ ::testing::internal::MakeAndRegisterTestInfo(\ #test_case_name, #test_name, NULL, NULL, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), \ (parent_id), \ parent_class::SetUpTestCase, \ parent_class::TearDownTestCase, \ @@ -1253,3 +1235,4 @@ class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ + diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-linked_ptr.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-linked_ptr.h index 57147b4e8be..36029422174 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-linked_ptr.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-linked_ptr.h @@ -105,25 +105,35 @@ class linked_ptr_internal { // framework. // Join an existing circle. - // L < g_linked_ptr_mutex - void join(linked_ptr_internal const* ptr) { + void join(linked_ptr_internal const* ptr) + GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { MutexLock lock(&g_linked_ptr_mutex); linked_ptr_internal const* p = ptr; - while (p->next_ != ptr) p = p->next_; + while (p->next_ != ptr) { + assert(p->next_ != this && + "Trying to join() a linked ring we are already in. " + "Is GMock thread safety enabled?"); + p = p->next_; + } p->next_ = this; next_ = ptr; } // Leave whatever circle we're part of. Returns true if we were the // last member of the circle. Once this is done, you can join() another. - // L < g_linked_ptr_mutex - bool depart() { + bool depart() + GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { MutexLock lock(&g_linked_ptr_mutex); if (next_ == this) return true; linked_ptr_internal const* p = next_; - while (p->next_ != this) p = p->next_; + while (p->next_ != this) { + assert(p->next_ != next_ && + "Trying to depart() a linked ring we are not in. " + "Is GMock thread safety enabled?"); + p = p->next_; + } p->next_ = next_; return false; } diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-param-util-generated.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-param-util-generated.h index e32c762f75a..4d1d81d20ff 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-param-util-generated.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-param-util-generated.h @@ -40,7 +40,7 @@ // and at most 10 arguments in Combine. Please contact // googletestframework@googlegroups.com if you need more. // Please note that the number of arguments to Combine is limited -// by the maximum arity of the implementation of tr1::tuple which is +// by the maximum arity of the implementation of tuple which is // currently set at 10. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ @@ -79,7 +79,10 @@ class ValueArray1 { explicit ValueArray1(T1 v1) : v1_(v1) {} template <typename T> - operator ParamGenerator<T>() const { return ValuesIn(&v1_, &v1_ + 1); } + operator ParamGenerator<T>() const { + const T array[] = {static_cast<T>(v1_)}; + return ValuesIn(array); + } private: // No implementation - assignment is unsupported. @@ -95,11 +98,14 @@ class ValueArray2 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_)}; return ValuesIn(array); } private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray2& other); + const T1 v1_; const T2 v2_; }; @@ -111,7 +117,8 @@ class ValueArray3 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_)}; return ValuesIn(array); } @@ -132,7 +139,8 @@ class ValueArray4 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_)}; return ValuesIn(array); } @@ -154,7 +162,8 @@ class ValueArray5 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_)}; return ValuesIn(array); } @@ -178,7 +187,9 @@ class ValueArray6 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_)}; return ValuesIn(array); } @@ -203,7 +214,9 @@ class ValueArray7 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_)}; return ValuesIn(array); } @@ -230,7 +243,9 @@ class ValueArray8 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_)}; return ValuesIn(array); } @@ -258,7 +273,10 @@ class ValueArray9 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_)}; return ValuesIn(array); } @@ -287,7 +305,10 @@ class ValueArray10 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_)}; return ValuesIn(array); } @@ -318,7 +339,10 @@ class ValueArray11 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_)}; return ValuesIn(array); } @@ -350,8 +374,11 @@ class ValueArray12 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_)}; return ValuesIn(array); } @@ -385,8 +412,11 @@ class ValueArray13 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_)}; return ValuesIn(array); } @@ -421,8 +451,11 @@ class ValueArray14 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_)}; return ValuesIn(array); } @@ -458,8 +491,12 @@ class ValueArray15 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_)}; return ValuesIn(array); } @@ -498,8 +535,12 @@ class ValueArray16 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_)}; return ValuesIn(array); } @@ -539,8 +580,12 @@ class ValueArray17 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_)}; return ValuesIn(array); } @@ -581,8 +626,13 @@ class ValueArray18 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_)}; return ValuesIn(array); } @@ -624,8 +674,13 @@ class ValueArray19 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_)}; return ValuesIn(array); } @@ -669,8 +724,13 @@ class ValueArray20 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_)}; return ValuesIn(array); } @@ -716,8 +776,14 @@ class ValueArray21 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_)}; return ValuesIn(array); } @@ -764,8 +830,14 @@ class ValueArray22 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_)}; return ValuesIn(array); } @@ -814,9 +886,14 @@ class ValueArray23 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, - v23_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_)}; return ValuesIn(array); } @@ -866,9 +943,15 @@ class ValueArray24 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_)}; return ValuesIn(array); } @@ -919,9 +1002,15 @@ class ValueArray25 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_)}; return ValuesIn(array); } @@ -974,9 +1063,15 @@ class ValueArray26 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_)}; return ValuesIn(array); } @@ -1031,9 +1126,16 @@ class ValueArray27 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_)}; return ValuesIn(array); } @@ -1089,9 +1191,16 @@ class ValueArray28 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_)}; return ValuesIn(array); } @@ -1148,9 +1257,16 @@ class ValueArray29 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_)}; return ValuesIn(array); } @@ -1209,9 +1325,17 @@ class ValueArray30 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_)}; return ValuesIn(array); } @@ -1272,9 +1396,17 @@ class ValueArray31 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_)}; return ValuesIn(array); } @@ -1336,9 +1468,17 @@ class ValueArray32 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_)}; return ValuesIn(array); } @@ -1402,9 +1542,18 @@ class ValueArray33 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_)}; return ValuesIn(array); } @@ -1469,9 +1618,18 @@ class ValueArray34 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_)}; return ValuesIn(array); } @@ -1537,10 +1695,18 @@ class ValueArray35 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, - v35_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_)}; return ValuesIn(array); } @@ -1608,10 +1774,19 @@ class ValueArray36 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_)}; return ValuesIn(array); } @@ -1681,10 +1856,19 @@ class ValueArray37 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_)}; return ValuesIn(array); } @@ -1755,10 +1939,19 @@ class ValueArray38 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_)}; return ValuesIn(array); } @@ -1830,10 +2023,20 @@ class ValueArray39 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_)}; return ValuesIn(array); } @@ -1907,10 +2110,20 @@ class ValueArray40 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_)}; return ValuesIn(array); } @@ -1986,10 +2199,20 @@ class ValueArray41 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_)}; return ValuesIn(array); } @@ -2066,10 +2289,21 @@ class ValueArray42 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), + static_cast<T>(v42_)}; return ValuesIn(array); } @@ -2147,10 +2381,21 @@ class ValueArray43 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), + static_cast<T>(v42_), static_cast<T>(v43_)}; return ValuesIn(array); } @@ -2230,10 +2475,21 @@ class ValueArray44 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), + static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_)}; return ValuesIn(array); } @@ -2314,10 +2570,22 @@ class ValueArray45 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), + static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), + static_cast<T>(v45_)}; return ValuesIn(array); } @@ -2400,10 +2668,22 @@ class ValueArray46 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), + static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), + static_cast<T>(v45_), static_cast<T>(v46_)}; return ValuesIn(array); } @@ -2488,11 +2768,22 @@ class ValueArray47 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, - v47_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), + static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), + static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_)}; return ValuesIn(array); } @@ -2578,11 +2869,23 @@ class ValueArray48 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, - v48_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), + static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), + static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_), + static_cast<T>(v48_)}; return ValuesIn(array); } @@ -2669,11 +2972,23 @@ class ValueArray49 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, - v48_, v49_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), + static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), + static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_), + static_cast<T>(v48_), static_cast<T>(v49_)}; return ValuesIn(array); } @@ -2761,11 +3076,23 @@ class ValueArray50 { template <typename T> operator ParamGenerator<T>() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, - v48_, v49_, v50_}; + const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), + static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), + static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), + static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), + static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), + static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), + static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), + static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), + static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), + static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), + static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), + static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), + static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), + static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), + static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), + static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_), + static_cast<T>(v48_), static_cast<T>(v49_), static_cast<T>(v50_)}; return ValuesIn(array); } @@ -2833,9 +3160,9 @@ class ValueArray50 { // template <typename T1, typename T2> class CartesianProductGenerator2 - : public ParamGeneratorInterface< ::std::tr1::tuple<T1, T2> > { + : public ParamGeneratorInterface< ::testing::tuple<T1, T2> > { public: - typedef ::std::tr1::tuple<T1, T2> ParamType; + typedef ::testing::tuple<T1, T2> ParamType; CartesianProductGenerator2(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2) @@ -2948,9 +3275,9 @@ class CartesianProductGenerator2 template <typename T1, typename T2, typename T3> class CartesianProductGenerator3 - : public ParamGeneratorInterface< ::std::tr1::tuple<T1, T2, T3> > { + : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3> > { public: - typedef ::std::tr1::tuple<T1, T2, T3> ParamType; + typedef ::testing::tuple<T1, T2, T3> ParamType; CartesianProductGenerator3(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3) @@ -3080,9 +3407,9 @@ class CartesianProductGenerator3 template <typename T1, typename T2, typename T3, typename T4> class CartesianProductGenerator4 - : public ParamGeneratorInterface< ::std::tr1::tuple<T1, T2, T3, T4> > { + : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4> > { public: - typedef ::std::tr1::tuple<T1, T2, T3, T4> ParamType; + typedef ::testing::tuple<T1, T2, T3, T4> ParamType; CartesianProductGenerator4(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, @@ -3231,9 +3558,9 @@ class CartesianProductGenerator4 template <typename T1, typename T2, typename T3, typename T4, typename T5> class CartesianProductGenerator5 - : public ParamGeneratorInterface< ::std::tr1::tuple<T1, T2, T3, T4, T5> > { + : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5> > { public: - typedef ::std::tr1::tuple<T1, T2, T3, T4, T5> ParamType; + typedef ::testing::tuple<T1, T2, T3, T4, T5> ParamType; CartesianProductGenerator5(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, @@ -3399,10 +3726,10 @@ class CartesianProductGenerator5 template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> class CartesianProductGenerator6 - : public ParamGeneratorInterface< ::std::tr1::tuple<T1, T2, T3, T4, T5, + : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6> > { public: - typedef ::std::tr1::tuple<T1, T2, T3, T4, T5, T6> ParamType; + typedef ::testing::tuple<T1, T2, T3, T4, T5, T6> ParamType; CartesianProductGenerator6(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, @@ -3585,10 +3912,10 @@ class CartesianProductGenerator6 template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> class CartesianProductGenerator7 - : public ParamGeneratorInterface< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, + : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7> > { public: - typedef ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7> ParamType; + typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7> ParamType; CartesianProductGenerator7(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, @@ -3788,10 +4115,10 @@ class CartesianProductGenerator7 template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> class CartesianProductGenerator8 - : public ParamGeneratorInterface< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, + : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8> > { public: - typedef ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8> ParamType; + typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8> ParamType; CartesianProductGenerator8(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, @@ -4010,10 +4337,10 @@ class CartesianProductGenerator8 template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> class CartesianProductGenerator9 - : public ParamGeneratorInterface< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, + : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> > { public: - typedef ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> ParamType; + typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> ParamType; CartesianProductGenerator9(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, @@ -4249,10 +4576,10 @@ class CartesianProductGenerator9 template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> class CartesianProductGenerator10 - : public ParamGeneratorInterface< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, + : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> > { public: - typedef ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> ParamType; + typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> ParamType; CartesianProductGenerator10(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, @@ -4514,8 +4841,8 @@ class CartesianProductHolder2 { CartesianProductHolder2(const Generator1& g1, const Generator2& g2) : g1_(g1), g2_(g2) {} template <typename T1, typename T2> - operator ParamGenerator< ::std::tr1::tuple<T1, T2> >() const { - return ParamGenerator< ::std::tr1::tuple<T1, T2> >( + operator ParamGenerator< ::testing::tuple<T1, T2> >() const { + return ParamGenerator< ::testing::tuple<T1, T2> >( new CartesianProductGenerator2<T1, T2>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_))); @@ -4536,8 +4863,8 @@ CartesianProductHolder3(const Generator1& g1, const Generator2& g2, const Generator3& g3) : g1_(g1), g2_(g2), g3_(g3) {} template <typename T1, typename T2, typename T3> - operator ParamGenerator< ::std::tr1::tuple<T1, T2, T3> >() const { - return ParamGenerator< ::std::tr1::tuple<T1, T2, T3> >( + operator ParamGenerator< ::testing::tuple<T1, T2, T3> >() const { + return ParamGenerator< ::testing::tuple<T1, T2, T3> >( new CartesianProductGenerator3<T1, T2, T3>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), @@ -4561,8 +4888,8 @@ CartesianProductHolder4(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4) : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} template <typename T1, typename T2, typename T3, typename T4> - operator ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4> >() const { - return ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4> >( + operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4> >() const { + return ParamGenerator< ::testing::tuple<T1, T2, T3, T4> >( new CartesianProductGenerator4<T1, T2, T3, T4>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), @@ -4588,8 +4915,8 @@ CartesianProductHolder5(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} template <typename T1, typename T2, typename T3, typename T4, typename T5> - operator ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5> >() const { - return ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5> >( + operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5> >() const { + return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5> >( new CartesianProductGenerator5<T1, T2, T3, T4, T5>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), @@ -4619,8 +4946,8 @@ CartesianProductHolder6(const Generator1& g1, const Generator2& g2, : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> - operator ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6> >() const { - return ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6> >( + operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6> >() const { + return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6> >( new CartesianProductGenerator6<T1, T2, T3, T4, T5, T6>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), @@ -4652,9 +4979,9 @@ CartesianProductHolder7(const Generator1& g1, const Generator2& g2, : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> - operator ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, + operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7> >() const { - return ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7> >( + return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7> >( new CartesianProductGenerator7<T1, T2, T3, T4, T5, T6, T7>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), @@ -4690,9 +5017,9 @@ CartesianProductHolder8(const Generator1& g1, const Generator2& g2, g8_(g8) {} template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> - operator ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, + operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8> >() const { - return ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8> >( + return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8> >( new CartesianProductGenerator8<T1, T2, T3, T4, T5, T6, T7, T8>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), @@ -4731,9 +5058,9 @@ CartesianProductHolder9(const Generator1& g1, const Generator2& g2, g9_(g9) {} template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> - operator ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, + operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> >() const { - return ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, + return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> >( new CartesianProductGenerator9<T1, T2, T3, T4, T5, T6, T7, T8, T9>( static_cast<ParamGenerator<T1> >(g1_), @@ -4775,10 +5102,10 @@ CartesianProductHolder10(const Generator1& g1, const Generator2& g2, g9_(g9), g10_(g10) {} template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> - operator ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, - T9, T10> >() const { - return ParamGenerator< ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, - T9, T10> >( + operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, + T10> >() const { + return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, + T10> >( new CartesianProductGenerator10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( static_cast<ParamGenerator<T1> >(g1_), diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-param-util.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-param-util.h index dea4d5cc6bc..82cab9b0201 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-param-util.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-param-util.h @@ -34,7 +34,10 @@ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ +#include <ctype.h> + #include <iterator> +#include <set> #include <utility> #include <vector> @@ -49,6 +52,27 @@ #if GTEST_HAS_PARAM_TEST namespace testing { + +// Input to a parameterized test name generator, describing a test parameter. +// Consists of the parameter value and the integer parameter index. +template <class ParamType> +struct TestParamInfo { + TestParamInfo(const ParamType& a_param, size_t an_index) : + param(a_param), + index(an_index) {} + ParamType param; + size_t index; +}; + +// A builtin parameterized test name generator which returns the result of +// testing::PrintToString. +struct PrintToStringParamName { + template <class ParamType> + std::string operator()(const TestParamInfo<ParamType>& info) const { + return PrintToString(info.param); + } +}; + namespace internal { // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. @@ -58,7 +82,7 @@ namespace internal { // TEST_P macro is used to define two tests with the same name // but in different namespaces. GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, - const char* file, int line); + CodeLocation code_location); template <typename> class ParamGeneratorInterface; template <typename> class ParamGenerator; @@ -206,7 +230,7 @@ class RangeGenerator : public ParamGeneratorInterface<T> { return base_; } virtual void Advance() { - value_ = value_ + step_; + value_ = static_cast<T>(value_ + step_); index_++; } virtual ParamIteratorInterface<T>* Clone() const { @@ -243,7 +267,7 @@ class RangeGenerator : public ParamGeneratorInterface<T> { const T& end, const IncrementT& step) { int end_index = 0; - for (T i = begin; i < end; i = i + step) + for (T i = begin; i < end; i = static_cast<T>(i + step)) end_index++; return end_index; } @@ -270,12 +294,12 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { template <typename ForwardIterator> ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) : container_(begin, end) {} - ~ValuesInIteratorRangeGenerator() override {} + virtual ~ValuesInIteratorRangeGenerator() {} - ParamIteratorInterface<T> *Begin() const override { + virtual ParamIteratorInterface<T>* Begin() const { return new Iterator(this, container_.begin()); } - ParamIteratorInterface<T> *End() const override { + virtual ParamIteratorInterface<T>* End() const { return new Iterator(this, container_.end()); } @@ -287,16 +311,16 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { Iterator(const ParamGeneratorInterface<T>* base, typename ContainerType::const_iterator iterator) : base_(base), iterator_(iterator) {} - ~Iterator() override {} + virtual ~Iterator() {} - const ParamGeneratorInterface<T> *BaseGenerator() const override { + virtual const ParamGeneratorInterface<T>* BaseGenerator() const { return base_; } - void Advance() override { + virtual void Advance() { ++iterator_; value_.reset(); } - ParamIteratorInterface<T> *Clone() const override { + virtual ParamIteratorInterface<T>* Clone() const { return new Iterator(*this); } // We need to use cached value referenced by iterator_ because *iterator_ @@ -306,12 +330,12 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { // can advance iterator_ beyond the end of the range, and we cannot // detect that fact. The client code, on the other hand, is // responsible for not calling Current() on an out-of-range iterator. - const T *Current() const override { + virtual const T* Current() const { if (value_.get() == NULL) value_.reset(new T(*iterator_)); return value_.get(); } - bool Equals(const ParamIteratorInterface<T> &other) const override { + virtual bool Equals(const ParamIteratorInterface<T>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) @@ -347,6 +371,37 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // +// Default parameterized test name generator, returns a string containing the +// integer test parameter index. +template <class ParamType> +std::string DefaultParamName(const TestParamInfo<ParamType>& info) { + Message name_stream; + name_stream << info.index; + return name_stream.GetString(); +} + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Parameterized test name overload helpers, which help the +// INSTANTIATE_TEST_CASE_P macro choose between the default parameterized +// test name generator and user param name generator. +template <class ParamType, class ParamNameGenFunctor> +ParamNameGenFunctor GetParamNameGen(ParamNameGenFunctor func) { + return func; +} + +template <class ParamType> +struct ParamNameGenFunc { + typedef std::string Type(const TestParamInfo<ParamType>&); +}; + +template <class ParamType> +typename ParamNameGenFunc<ParamType>::Type *GetParamNameGen() { + return DefaultParamName; +} + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// // Stores a parameter value and later creates tests parameterized with that // value. template <class TestClass> @@ -355,7 +410,7 @@ class ParameterizedTestFactory : public TestFactoryBase { typedef typename TestClass::ParamType ParamType; explicit ParameterizedTestFactory(ParamType parameter) : parameter_(parameter) {} - Test *CreateTest() override { + virtual Test* CreateTest() { TestClass::SetParam(¶meter_); return new TestClass(); } @@ -394,7 +449,7 @@ class TestMetaFactory TestMetaFactory() {} - TestFactoryBase *CreateTestFactory(ParamType parameter) override { + virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { return new ParameterizedTestFactory<TestCase>(parameter); } @@ -414,7 +469,7 @@ class TestMetaFactory // and calls RegisterTests() on each of them when asked. class ParameterizedTestCaseInfoBase { public: - virtual ~ParameterizedTestCaseInfoBase(); + virtual ~ParameterizedTestCaseInfoBase() {} // Base part of test case name for display purposes. virtual const string& GetTestCaseName() const = 0; @@ -449,14 +504,16 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { typedef typename TestCase::ParamType ParamType; // A function that returns an instance of appropriate generator type. typedef ParamGenerator<ParamType>(GeneratorCreationFunc)(); + typedef typename ParamNameGenFunc<ParamType>::Type ParamNameGeneratorFunc; - explicit ParameterizedTestCaseInfo(const char* name) - : test_case_name_(name) {} + explicit ParameterizedTestCaseInfo( + const char* name, CodeLocation code_location) + : test_case_name_(name), code_location_(code_location) {} // Test case base name for display purposes. - const string &GetTestCaseName() const override { return test_case_name_; } + virtual const string& GetTestCaseName() const { return test_case_name_; } // Test case id to verify identity. - TypeId GetTestCaseTypeId() const override { return GetTypeId<TestCase>(); } + virtual TypeId GetTestCaseTypeId() const { return GetTypeId<TestCase>(); } // TEST_P macro uses AddTestPattern() to record information // about a single test in a LocalTestInfo structure. // test_case_name is the base name of the test case (without invocation @@ -474,9 +531,11 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { // about a generator. int AddTestCaseInstantiation(const string& instantiation_name, GeneratorCreationFunc* func, - const char* /* file */, - int /* line */) { - instantiations_.push_back(::std::make_pair(instantiation_name, func)); + ParamNameGeneratorFunc* name_func, + const char* file, + int line) { + instantiations_.push_back( + InstantiationInfo(instantiation_name, func, name_func, file, line)); return 0; // Return value used only to run this method in namespace scope. } // UnitTest class invokes this method to register tests in this test case @@ -484,32 +543,52 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { // This method should not be called more then once on any single // instance of a ParameterizedTestCaseInfoBase derived class. // UnitTest has a guard to prevent from calling this method more then once. - void RegisterTests() override { + virtual void RegisterTests() { for (typename TestInfoContainer::iterator test_it = tests_.begin(); test_it != tests_.end(); ++test_it) { linked_ptr<TestInfo> test_info = *test_it; for (typename InstantiationContainer::iterator gen_it = instantiations_.begin(); gen_it != instantiations_.end(); ++gen_it) { - const string& instantiation_name = gen_it->first; - ParamGenerator<ParamType> generator((*gen_it->second)()); + const string& instantiation_name = gen_it->name; + ParamGenerator<ParamType> generator((*gen_it->generator)()); + ParamNameGeneratorFunc* name_func = gen_it->name_func; + const char* file = gen_it->file; + int line = gen_it->line; - Message test_case_name_stream; + string test_case_name; if ( !instantiation_name.empty() ) - test_case_name_stream << instantiation_name << "/"; - test_case_name_stream << test_info->test_case_base_name; + test_case_name = instantiation_name + "/"; + test_case_name += test_info->test_case_base_name; - int i = 0; + size_t i = 0; + std::set<std::string> test_param_names; for (typename ParamGenerator<ParamType>::iterator param_it = generator.begin(); param_it != generator.end(); ++param_it, ++i) { Message test_name_stream; - test_name_stream << test_info->test_base_name << "/" << i; + + std::string param_name = name_func( + TestParamInfo<ParamType>(*param_it, i)); + + GTEST_CHECK_(IsValidParamName(param_name)) + << "Parameterized test name '" << param_name + << "' is invalid, in " << file + << " line " << line << std::endl; + + GTEST_CHECK_(test_param_names.count(param_name) == 0) + << "Duplicate parameterized test name '" << param_name + << "', in " << file << " line " << line << std::endl; + + test_param_names.insert(param_name); + + test_name_stream << test_info->test_base_name << "/" << param_name; MakeAndRegisterTestInfo( - test_case_name_stream.GetString().c_str(), + test_case_name.c_str(), test_name_stream.GetString().c_str(), NULL, // No type parameter. PrintToString(*param_it).c_str(), + code_location_, GetTestCaseTypeId(), TestCase::SetUpTestCase, TestCase::TearDownTestCase, @@ -535,12 +614,45 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory; }; typedef ::std::vector<linked_ptr<TestInfo> > TestInfoContainer; - // Keeps pairs of <Instantiation name, Sequence generator creation function> - // received from INSTANTIATE_TEST_CASE_P macros. - typedef ::std::vector<std::pair<string, GeneratorCreationFunc*> > - InstantiationContainer; + // Records data received from INSTANTIATE_TEST_CASE_P macros: + // <Instantiation name, Sequence generator creation function, + // Name generator function, Source file, Source line> + struct InstantiationInfo { + InstantiationInfo(const std::string &name_in, + GeneratorCreationFunc* generator_in, + ParamNameGeneratorFunc* name_func_in, + const char* file_in, + int line_in) + : name(name_in), + generator(generator_in), + name_func(name_func_in), + file(file_in), + line(line_in) {} + + std::string name; + GeneratorCreationFunc* generator; + ParamNameGeneratorFunc* name_func; + const char* file; + int line; + }; + typedef ::std::vector<InstantiationInfo> InstantiationContainer; + + static bool IsValidParamName(const std::string& name) { + // Check for empty string + if (name.empty()) + return false; + + // Check for invalid characters + for (std::string::size_type index = 0; index < name.size(); ++index) { + if (!isalnum(name[index]) && name[index] != '_') + return false; + } + + return true; + } const string test_case_name_; + CodeLocation code_location_; TestInfoContainer tests_; InstantiationContainer instantiations_; @@ -568,8 +680,7 @@ class ParameterizedTestCaseRegistry { template <class TestCase> ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder( const char* test_case_name, - const char* file, - int line) { + CodeLocation code_location) { ParameterizedTestCaseInfo<TestCase>* typed_test_info = NULL; for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { @@ -578,7 +689,7 @@ class ParameterizedTestCaseRegistry { // Complain about incorrect usage of Google Test facilities // and terminate the program since we cannot guaranty correct // test case setup and tear-down in this case. - ReportInvalidTestCaseType(test_case_name, file, line); + ReportInvalidTestCaseType(test_case_name, code_location); posix::Abort(); } else { // At this point we are sure that the object we found is of the same @@ -591,7 +702,8 @@ class ParameterizedTestCaseRegistry { } } if (typed_test_info == NULL) { - typed_test_info = new ParameterizedTestCaseInfo<TestCase>(test_case_name); + typed_test_info = new ParameterizedTestCaseInfo<TestCase>( + test_case_name, code_location); test_case_infos_.push_back(typed_test_info); } return typed_test_info; diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-port-arch.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-port-arch.h new file mode 100644 index 00000000000..a375b73799b --- /dev/null +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-port-arch.h @@ -0,0 +1,97 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the GTEST_OS_* macro. +// It is separate from gtest-port.h so that custom/gtest-port.h can include it. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ + +// Determines the platform on which Google Test is compiled. +#ifdef __CYGWIN__ +# define GTEST_OS_CYGWIN 1 +#elif defined __SYMBIAN32__ +# define GTEST_OS_SYMBIAN 1 +#elif defined _WIN32 +# define GTEST_OS_WINDOWS 1 +# ifdef _WIN32_WCE +# define GTEST_OS_WINDOWS_MOBILE 1 +# elif defined(__MINGW__) || defined(__MINGW32__) +# define GTEST_OS_WINDOWS_MINGW 1 +# elif defined(WINAPI_FAMILY) +# include <winapifamily.h> +# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +# define GTEST_OS_WINDOWS_DESKTOP 1 +# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) +# define GTEST_OS_WINDOWS_PHONE 1 +# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) +# define GTEST_OS_WINDOWS_RT 1 +# else + // WINAPI_FAMILY defined but no known partition matched. + // Default to desktop. +# define GTEST_OS_WINDOWS_DESKTOP 1 +# endif +# else +# define GTEST_OS_WINDOWS_DESKTOP 1 +# endif // _WIN32_WCE +#elif defined __APPLE__ +# define GTEST_OS_MAC 1 +# if TARGET_OS_IPHONE +# define GTEST_OS_IOS 1 +# endif +#elif defined __FreeBSD__ +# define GTEST_OS_FREEBSD 1 +#elif defined __linux__ +# define GTEST_OS_LINUX 1 +# if defined __ANDROID__ +# define GTEST_OS_LINUX_ANDROID 1 +# endif +#elif defined __MVS__ +# define GTEST_OS_ZOS 1 +#elif defined(__sun) && defined(__SVR4) +# define GTEST_OS_SOLARIS 1 +#elif defined(_AIX) +# define GTEST_OS_AIX 1 +#elif defined(__hpux) +# define GTEST_OS_HPUX 1 +#elif defined __native_client__ +# define GTEST_OS_NACL 1 +#elif defined __OpenBSD__ +# define GTEST_OS_OPENBSD 1 +#elif defined __QNX__ +# define GTEST_OS_QNX 1 +#elif defined(__HAIKU__) +# define GTEST_OS_HAIKU 1 +#elif defined(_MINIX) +# define GTEST_OS_MINIX 1 +#endif // __CYGWIN__ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-port.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-port.h index cac04a7bb72..8762f974ef8 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-port.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-port.h @@ -30,15 +30,43 @@ // Authors: wan@google.com (Zhanyong Wan) // // Low-level types and utilities for porting Google Test to various -// platforms. They are subject to change without notice. DO NOT USE -// THEM IN USER CODE. +// platforms. All macros ending with _ and symbols defined in an +// internal namespace are subject to change without notice. Code +// outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't +// end with _ are part of Google Test's public API and can be used by +// code outside Google Test. +// +// This file is fundamental to Google Test. All other Google Test source +// files are expected to #include this. Therefore, it cannot #include +// any other Google Test header. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ -// The user can define the following macros in the build script to -// control Google Test's behavior. If the user doesn't define a macro -// in this list, Google Test will define it. +// Environment-describing macros +// ----------------------------- +// +// Google Test can be used in many different environments. Macros in +// this section tell Google Test what kind of environment it is being +// used in, such that Google Test can provide environment-specific +// features and implementations. +// +// Google Test tries to automatically detect the properties of its +// environment, so users usually don't need to worry about these +// macros. However, the automatic detection is not perfect. +// Sometimes it's necessary for a user to define some of the following +// macros in the build script to override Google Test's decisions. +// +// If the user doesn't define a macro in the list, Google Test will +// provide a default definition. After this header is #included, all +// macros in this list will be defined to either 1 or 0. +// +// Notes to maintainers: +// - Each macro here is a user-tweakable knob; do not grow the list +// lightly. +// - Use #if to key off these macros. Don't use #ifdef or "#if +// defined(...)", which will not work as these macros are ALWAYS +// defined. // // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) // is/isn't available. @@ -72,6 +100,8 @@ // Test's own tr1 tuple implementation should be // used. Unused when the user sets // GTEST_HAS_TR1_TUPLE to 0. +// GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test +// is building in C++11/C++98 mode. // GTEST_LINKED_AS_SHARED_LIBRARY // - Define to 1 when compiling tests that use // Google Test as a shared library (known as @@ -80,10 +110,15 @@ // - Define to 1 when compiling Google Test itself // as a shared library. -// This header defines the following utilities: +// Platform-indicating macros +// -------------------------- +// +// Macros indicating the platform on which Google Test is being used +// (a macro is defined to 1 if compiled on the given platform; +// otherwise UNDEFINED -- it's never defined to 0.). Google Test +// defines these macros automatically. Code outside Google Test MUST +// NOT define them. // -// Macros indicating the current platform (defined to 1 if compiled on -// the given platform; otherwise undefined): // GTEST_OS_AIX - IBM AIX // GTEST_OS_CYGWIN - Cygwin // GTEST_OS_FREEBSD - FreeBSD @@ -92,14 +127,19 @@ // GTEST_OS_LINUX - Linux // GTEST_OS_LINUX_ANDROID - Google Android // GTEST_OS_MAC - Mac OS X +// GTEST_OS_IOS - iOS // GTEST_OS_MINIX - Minix // GTEST_OS_NACL - Google Native Client (NaCl) +// GTEST_OS_OPENBSD - OpenBSD +// GTEST_OS_QNX - QNX // GTEST_OS_SOLARIS - Sun Solaris // GTEST_OS_SYMBIAN - Symbian // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop // GTEST_OS_WINDOWS_MINGW - MinGW // GTEST_OS_WINDOWS_MOBILE - Windows Mobile +// GTEST_OS_WINDOWS_PHONE - Windows Phone +// GTEST_OS_WINDOWS_RT - Windows Store App/WinRT // GTEST_OS_ZOS - z/OS // // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the @@ -109,22 +149,50 @@ // googletestframework@googlegroups.com (patches for fixing them are // even more welcome!). // -// Note that it is possible that none of the GTEST_OS_* macros are defined. +// It is possible that none of the GTEST_OS_* macros are defined. + +// Feature-indicating macros +// ------------------------- +// +// Macros indicating which Google Test features are available (a macro +// is defined to 1 if the corresponding feature is supported; +// otherwise UNDEFINED -- it's never defined to 0.). Google Test +// defines these macros automatically. Code outside Google Test MUST +// NOT define them. +// +// These macros are public so that portable tests can be written. +// Such tests typically surround code using a feature with an #if +// which controls that code. For example: +// +// #if GTEST_HAS_DEATH_TEST +// EXPECT_DEATH(DoSomethingDeadly()); +// #endif // -// Macros indicating available Google Test features (defined to 1 if -// the corresponding feature is supported; otherwise undefined): // GTEST_HAS_COMBINE - the Combine() function (for value-parameterized // tests) // GTEST_HAS_DEATH_TEST - death tests // GTEST_HAS_PARAM_TEST - value-parameterized tests // GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests +// GTEST_IS_THREADSAFE - Google Test is thread-safe. // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with // GTEST_HAS_POSIX_RE (see above) which users can // define themselves. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above two are mutually exclusive. // GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). + +// Misc public macros +// ------------------ +// +// GTEST_FLAG(flag_name) - references the variable corresponding to +// the given Google Test flag. + +// Internal utilities +// ------------------ +// +// The following macros and utilities are for Google Test's INTERNAL +// use only. Code outside Google Test MUST NOT USE THEM DIRECTLY. // // Macros for basic C++ coding: // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. @@ -133,13 +201,18 @@ // GTEST_DISALLOW_ASSIGN_ - disables operator=. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. +// GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is +// suppressed (constant conditional). +// GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127 +// is suppressed. +// +// C++11 feature wrappers: +// +// testing::internal::move - portability wrapper for std::move. // // Synchronization: // Mutex, MutexLock, ThreadLocal, GetThreadCount() -// - synchronization primitives. -// GTEST_IS_THREADSAFE - defined to 1 to indicate that the above -// synchronization primitives have real implementations -// and Google Test is thread-safe; or 0 otherwise. +// - synchronization primitives. // // Template meta programming: // is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. @@ -175,10 +248,9 @@ // BiggestInt - the biggest signed integer type. // // Command-line utilities: -// GTEST_FLAG() - references a flag. // GTEST_DECLARE_*() - declares a flag. // GTEST_DEFINE_*() - defines a flag. -// GetArgvs() - returns the command line as a vector of strings. +// GetInjectableArgvs() - returns the command line as a vector of strings. // // Environment variable utilities: // GetEnv() - gets the value of an environment variable. @@ -196,16 +268,33 @@ # include <sys/stat.h> #endif // !_WIN32_WCE +#if defined __APPLE__ +# include <AvailabilityMacros.h> +# include <TargetConditionals.h> +#endif + +#include <algorithm> // NOLINT #include <iostream> // NOLINT #include <sstream> // NOLINT #include <string> // NOLINT +#include <utility> +#include <vector> // NOLINT + +#include "gtest/internal/gtest-port-arch.h" +#include "gtest/internal/custom/gtest-port.h" + +#if !defined(GTEST_DEV_EMAIL_) +# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" +# define GTEST_FLAG_PREFIX_ "gtest_" +# define GTEST_FLAG_PREFIX_DASH_ "gtest-" +# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" +# define GTEST_NAME_ "Google Test" +# define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" +#endif // !defined(GTEST_DEV_EMAIL_) -#define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" -#define GTEST_FLAG_PREFIX_ "gtest_" -#define GTEST_FLAG_PREFIX_DASH_ "gtest-" -#define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" -#define GTEST_NAME_ "Google Test" -#define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/" +#if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) +# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" +#endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) // Determines the version of gcc that is used to compile this. #ifdef __GNUC__ @@ -214,70 +303,132 @@ (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) #endif // __GNUC__ -// Determines the platform on which Google Test is compiled. -#ifdef __CYGWIN__ -# define GTEST_OS_CYGWIN 1 -#elif defined __SYMBIAN32__ -# define GTEST_OS_SYMBIAN 1 -#elif defined _WIN32 -# define GTEST_OS_WINDOWS 1 -# ifdef _WIN32_WCE -# define GTEST_OS_WINDOWS_MOBILE 1 -# elif defined(__MINGW__) || defined(__MINGW32__) -# define GTEST_OS_WINDOWS_MINGW 1 +// Macros for disabling Microsoft Visual C++ warnings. +// +// GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385) +// /* code that triggers warnings C4800 and C4385 */ +// GTEST_DISABLE_MSC_WARNINGS_POP_() +#if _MSC_VER >= 1500 +# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ + __pragma(warning(push)) \ + __pragma(warning(disable: warnings)) +# define GTEST_DISABLE_MSC_WARNINGS_POP_() \ + __pragma(warning(pop)) +#else +// Older versions of MSVC don't have __pragma. +# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) +# define GTEST_DISABLE_MSC_WARNINGS_POP_() +#endif + +#ifndef GTEST_LANG_CXX11 +// gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when +// -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a +// value for __cplusplus, and recent versions of clang, gcc, and +// probably other compilers set that too in C++11 mode. +# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L +// Compiling in at least C++11 mode. +# define GTEST_LANG_CXX11 1 # else -# define GTEST_OS_WINDOWS_DESKTOP 1 -# endif // _WIN32_WCE -#elif defined __APPLE__ -# define GTEST_OS_MAC 1 -#elif defined __FreeBSD__ -# define GTEST_OS_FREEBSD 1 -#elif defined __linux__ -# define GTEST_OS_LINUX 1 -# if defined(ANDROID) || defined(__ANDROID__) -# define GTEST_OS_LINUX_ANDROID 1 -# endif // ANDROID -#elif defined __MVS__ -# define GTEST_OS_ZOS 1 -#elif defined(__sun) && defined(__SVR4) -# define GTEST_OS_SOLARIS 1 -#elif defined(_AIX) -# define GTEST_OS_AIX 1 -#elif defined(__hpux) -# define GTEST_OS_HPUX 1 -#elif defined __native_client__ -# define GTEST_OS_NACL 1 -#elif defined(__HAIKU__) -# define GTEST_OS_HAIKU 1 -#elif defined(_MINIX) -# define GTEST_OS_MINIX 1 -#endif // __CYGWIN__ +# define GTEST_LANG_CXX11 0 +# endif +#endif + +// Distinct from C++11 language support, some environments don't provide +// proper C++11 library support. Notably, it's possible to build in +// C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++ +// with no C++11 support. +// +// libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__ +// 20110325, but maintenance releases in the 4.4 and 4.5 series followed +// this date, so check for those versions by their date stamps. +// https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning +#if GTEST_LANG_CXX11 && \ + (!defined(__GLIBCXX__) || ( \ + __GLIBCXX__ >= 20110325ul && /* GCC >= 4.6.0 */ \ + /* Blacklist of patch releases of older branches: */ \ + __GLIBCXX__ != 20110416ul && /* GCC 4.4.6 */ \ + __GLIBCXX__ != 20120313ul && /* GCC 4.4.7 */ \ + __GLIBCXX__ != 20110428ul && /* GCC 4.5.3 */ \ + __GLIBCXX__ != 20120702ul)) /* GCC 4.5.4 */ +# define GTEST_STDLIB_CXX11 1 +#endif + +// Only use C++11 library features if the library provides them. +#if GTEST_STDLIB_CXX11 +# define GTEST_HAS_STD_BEGIN_AND_END_ 1 +# define GTEST_HAS_STD_FORWARD_LIST_ 1 +# define GTEST_HAS_STD_FUNCTION_ 1 +# define GTEST_HAS_STD_INITIALIZER_LIST_ 1 +# define GTEST_HAS_STD_MOVE_ 1 +# define GTEST_HAS_STD_SHARED_PTR_ 1 +# define GTEST_HAS_STD_TYPE_TRAITS_ 1 +# define GTEST_HAS_STD_UNIQUE_PTR_ 1 +#endif + +// C++11 specifies that <tuple> provides std::tuple. +// Some platforms still might not have it, however. +#if GTEST_LANG_CXX11 +# define GTEST_HAS_STD_TUPLE_ 1 +# if defined(__clang__) +// Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include +# if defined(__has_include) && !__has_include(<tuple>) +# undef GTEST_HAS_STD_TUPLE_ +# endif +# elif defined(_MSC_VER) +// Inspired by boost/config/stdlib/dinkumware.hpp +# if defined(_CPPLIB_VER) && _CPPLIB_VER < 520 +# undef GTEST_HAS_STD_TUPLE_ +# endif +# elif defined(__GLIBCXX__) +// Inspired by boost/config/stdlib/libstdcpp3.hpp, +// http://gcc.gnu.org/gcc-4.2/changes.html and +// http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x +# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) +# undef GTEST_HAS_STD_TUPLE_ +# endif +# endif +#endif // Brings in definitions for functions used in the testing::internal::posix // namespace (read, write, close, chdir, isatty, stat). We do not currently // use them on Windows Mobile. -#if !GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS +# if !GTEST_OS_WINDOWS_MOBILE +# include <direct.h> +# include <io.h> +# endif +// In order to avoid having to include <windows.h>, use forward declaration +// assuming CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION. +// This assumption is verified by +// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION. +struct _RTL_CRITICAL_SECTION; +#else // This assumes that non-Windows OSes provide unistd.h. For OSes where this // is not the case, we need to include headers that provide the functions // mentioned above. # include <unistd.h> -# if !GTEST_OS_NACL -// TODO(vladl@google.com): Remove this condition when Native Client SDK adds -// strings.h (tracked in -// http://code.google.com/p/nativeclient/issues/detail?id=1175). -# include <strings.h> // Native Client doesn't provide strings.h. -# endif -#elif !GTEST_OS_WINDOWS_MOBILE -# include <direct.h> -# include <io.h> +# include <strings.h> +#endif // GTEST_OS_WINDOWS + +#if GTEST_OS_LINUX_ANDROID +// Used to define __ANDROID_API__ matching the target NDK API level. +# include <android/api-level.h> // NOLINT #endif // Defines this to true iff Google Test can use POSIX regular expressions. #ifndef GTEST_HAS_POSIX_RE -# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) +# if GTEST_OS_LINUX_ANDROID +// On Android, <regex.h> is only available starting with Gingerbread. +# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) +# else +# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) +# endif #endif -#if GTEST_HAS_POSIX_RE +#if GTEST_USES_PCRE +// The appropriate headers have already been included. + +#elif GTEST_HAS_POSIX_RE // On some platforms, <regex.h> needs someone to define size_t, and // won't compile otherwise. We can #include it here as we already @@ -299,7 +450,7 @@ // simple regex implementation instead. # define GTEST_USES_SIMPLE_RE 1 -#endif // GTEST_HAS_POSIX_RE +#endif // GTEST_USES_PCRE #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need @@ -312,6 +463,15 @@ # define _HAS_EXCEPTIONS 1 # endif // _HAS_EXCEPTIONS # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS +# elif defined(__clang__) +// clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714, +// but iff cleanups are enabled after that. In Obj-C++ files, there can be +// cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions +// are disabled. clang has __has_feature(cxx_exceptions) which checks for C++ +// exceptions starting at clang r206352, but which checked for cleanups prior to +// that. To reliably check for C++ exception availability with clang, check for +// __EXCEPTIONS && __has_feature(cxx_exceptions). +# define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) # elif defined(__GNUC__) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 @@ -390,11 +550,27 @@ # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) # ifdef __GXX_RTTI -# define GTEST_HAS_RTTI 1 +// When building against STLport with the Android NDK and with +// -frtti -fno-exceptions, the build fails at link time with undefined +// references to __cxa_bad_typeid. Note sure if STL or toolchain bug, +// so disable RTTI when detected. +# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ + !defined(__EXCEPTIONS) +# define GTEST_HAS_RTTI 0 +# else +# define GTEST_HAS_RTTI 1 +# endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS # else # define GTEST_HAS_RTTI 0 # endif // __GXX_RTTI +// Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends +// using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the +// first version with C++ support. +# elif defined(__clang__) + +# define GTEST_HAS_RTTI __has_feature(cxx_rtti) + // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if // both the typeid and dynamic_cast features are present. # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) @@ -422,13 +598,13 @@ // Determines whether Google Test can use the pthreads library. #ifndef GTEST_HAS_PTHREAD -// The user didn't tell us explicitly, so we assume pthreads support is -// available on Linux and Mac. +// The user didn't tell us explicitly, so we make reasonable assumptions about +// which platforms have pthreads support. // // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // to your compiler flags. -# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || \ - GTEST_OS_HPUX || GTEST_OS_FREEBSD) +# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \ + || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL) #endif // GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD @@ -440,12 +616,26 @@ # include <time.h> // NOLINT #endif +// Determines if hash_map/hash_set are available. +// Only used for testing against those containers. +#if !defined(GTEST_HAS_HASH_MAP_) +# if _MSC_VER +# define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. +# define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available. +# endif // _MSC_VER +#endif // !defined(GTEST_HAS_HASH_MAP_) + // Determines whether Google Test can use tr1/tuple. You can define // this macro to 0 to prevent Google Test from using tuple (any // feature depending on tuple with be disabled in this mode). #ifndef GTEST_HAS_TR1_TUPLE +# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) +// STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>. +# define GTEST_HAS_TR1_TUPLE 0 +# else // The user didn't tell us not to do it, so we assume it's OK. -# define GTEST_HAS_TR1_TUPLE 1 +# define GTEST_HAS_TR1_TUPLE 1 +# endif #endif // GTEST_HAS_TR1_TUPLE // Determines whether Google Test's own tr1 tuple implementation @@ -454,15 +644,28 @@ // The user didn't tell us, so we need to figure it out. // We use our own TR1 tuple if we aren't sure the user has an -// implementation of it already. At this time, GCC 4.0.0+ and MSVC -// 2010 are the only mainstream compilers that come with a TR1 tuple -// implementation. NVIDIA's CUDA NVCC compiler pretends to be GCC by -// defining __GNUC__ and friends, but cannot compile GCC's tuple -// implementation. MSVC 2008 (9.0) provides TR1 tuple in a 323 MB -// Feature Pack download, which we cannot assume the user has. -# if (defined(__GNUC__) && !(defined(__CUDACC__) || defined(__clang__)) \ - && (GTEST_GCC_VER_ >= 40000)) \ - || _MSC_VER >= 1600 +// implementation of it already. At this time, libstdc++ 4.0.0+ and +// MSVC 2010 are the only mainstream standard libraries that come +// with a TR1 tuple implementation. NVIDIA's CUDA NVCC compiler +// pretends to be GCC by defining __GNUC__ and friends, but cannot +// compile GCC's tuple implementation. MSVC 2008 (9.0) provides TR1 +// tuple in a 323 MB Feature Pack download, which we cannot assume the +// user has. QNX's QCC compiler is a modified GCC but it doesn't +// support TR1 tuple. libc++ only provides std::tuple, in C++11 mode, +// and it can be used with some compilers that define __GNUC__. +# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \ + && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600 +# define GTEST_ENV_HAS_TR1_TUPLE_ 1 +# endif + +// C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used +// in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6 +// can build with clang but need to use gcc4.2's libstdc++). +# if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325) +# define GTEST_ENV_HAS_STD_TUPLE_ 1 +# endif + +# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_ # define GTEST_USE_OWN_TR1_TUPLE 0 # else # define GTEST_USE_OWN_TR1_TUPLE 1 @@ -472,11 +675,37 @@ // To avoid conditional compilation everywhere, we make it // gtest-port.h's responsibility to #include the header implementing -// tr1/tuple. +// tuple. +#if GTEST_HAS_STD_TUPLE_ +# include <tuple> // IWYU pragma: export +# define GTEST_TUPLE_NAMESPACE_ ::std +#endif // GTEST_HAS_STD_TUPLE_ + +// We include tr1::tuple even if std::tuple is available to define printers for +// them. #if GTEST_HAS_TR1_TUPLE +# ifndef GTEST_TUPLE_NAMESPACE_ +# define GTEST_TUPLE_NAMESPACE_ ::std::tr1 +# endif // GTEST_TUPLE_NAMESPACE_ # if GTEST_USE_OWN_TR1_TUPLE -# include "gtest/internal/gtest-tuple.h" +# include "gtest/internal/gtest-tuple.h" // IWYU pragma: export // NOLINT +# elif GTEST_ENV_HAS_STD_TUPLE_ +# include <tuple> +// C++11 puts its tuple into the ::std namespace rather than +// ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there. +// This causes undefined behavior, but supported compilers react in +// the way we intend. +namespace std { +namespace tr1 { +using ::std::get; +using ::std::make_tuple; +using ::std::tuple; +using ::std::tuple_element; +using ::std::tuple_size; +} +} + # elif GTEST_OS_SYMBIAN // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to @@ -491,7 +720,7 @@ // This prevents <boost/tr1/detail/config.hpp>, which defines // BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>. # define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED -# include <tuple> +# include <tuple> // IWYU pragma: export // NOLINT # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) // GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header. This does @@ -506,7 +735,7 @@ # define _TR1_FUNCTIONAL 1 # include <tr1/tuple> # undef _TR1_FUNCTIONAL // Allows the user to #include - // <tr1/functional> if they choose to. + // <tr1/functional> if he chooses to. # else # include <tr1/tuple> // NOLINT # endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 @@ -514,7 +743,7 @@ # else // If the compiler is not GCC 4.0+, we assume the user is using a // spec-conforming TR1 implementation. -# include <tuple> // NOLINT +# include <tuple> // IWYU pragma: export // NOLINT # endif // GTEST_USE_OWN_TR1_TUPLE #endif // GTEST_HAS_TR1_TUPLE @@ -527,7 +756,16 @@ // The user didn't tell us, so we need to figure it out. # if GTEST_OS_LINUX && !defined(__ia64__) -# define GTEST_HAS_CLONE 1 +# if GTEST_OS_LINUX_ANDROID +// On Android, clone() is only available on ARM starting with Gingerbread. +# if defined(__arm__) && __ANDROID_API__ >= 9 +# define GTEST_HAS_CLONE 1 +# else +# define GTEST_HAS_CLONE 0 +# endif +# else +# define GTEST_HAS_CLONE 1 +# endif # else # define GTEST_HAS_CLONE 0 # endif // GTEST_OS_LINUX && !defined(__ia64__) @@ -539,7 +777,8 @@ #ifndef GTEST_HAS_STREAM_REDIRECTION // By default, we assume that stream redirection is supported on all // platforms except known mobile ones. -# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN +# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \ + GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT # define GTEST_HAS_STREAM_REDIRECTION 0 # else # define GTEST_HAS_STREAM_REDIRECTION 1 @@ -550,12 +789,12 @@ // Google Test does not support death tests for VC 7.1 and earlier as // abort() in a VC 7.1 application compiled as GUI in debug config // pops up a dialog window that cannot be suppressed programmatically. -#if (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ +#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ + (GTEST_OS_MAC && !GTEST_OS_IOS) || \ (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ - GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || \ - GTEST_OS_HPUX || GTEST_OS_FREEBSD) + GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ + GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD) # define GTEST_HAS_DEATH_TEST 1 -# include <vector> // NOLINT #endif // We don't support MSVC 7.1 with exceptions disabled now. Therefore @@ -619,7 +858,12 @@ // compiler the variable/parameter does not have to be used. #if defined(__GNUC__) && !defined(COMPILER_ICC) # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) -#else +#elif defined(__clang__) +# if __has_attribute(unused) +# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) +# endif +#endif +#ifndef GTEST_ATTRIBUTE_UNUSED_ # define GTEST_ATTRIBUTE_UNUSED_ #endif @@ -645,6 +889,19 @@ # define GTEST_MUST_USE_RESULT_ #endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC +// MS C++ compiler emits warning when a conditional expression is compile time +// constant. In some contexts this warning is false positive and needs to be +// suppressed. Use the following two macros in such cases: +// +// GTEST_INTENTIONAL_CONST_COND_PUSH_() +// while (true) { +// GTEST_INTENTIONAL_CONST_COND_POP_() +// } +# define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) +# define GTEST_INTENTIONAL_CONST_COND_POP_() \ + GTEST_DISABLE_MSC_WARNINGS_POP_() + // Determine whether the compiler supports Microsoft's Structured Exception // Handling. This is supported by several Windows compilers but generally // does not exist on any other system. @@ -661,15 +918,20 @@ #endif // GTEST_HAS_SEH -#ifdef _MSC_VER +#define GTEST_IS_THREADSAFE \ + (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \ + || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \ + || GTEST_HAS_PTHREAD) +#ifdef _MSC_VER # if GTEST_LINKED_AS_SHARED_LIBRARY # define GTEST_API_ __declspec(dllimport) # elif GTEST_CREATE_SHARED_LIBRARY # define GTEST_API_ __declspec(dllexport) # endif - -#endif // _MSC_VER +#elif __GNUC__ >= 4 || defined(__clang__) +# define GTEST_API_ __attribute__((visibility ("default"))) +#endif // _MSC_VER #ifndef GTEST_API_ # define GTEST_API_ @@ -682,20 +944,84 @@ # define GTEST_NO_INLINE_ #endif +// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. +#if defined(__has_include) +# if __has_include(<cxxabi.h>) +# define GTEST_HAS_CXXABI_H_ 1 +# else +# define GTEST_HAS_CXXABI_H_ 0 +# endif +#elif defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) +# define GTEST_HAS_CXXABI_H_ 1 +#else +# define GTEST_HAS_CXXABI_H_ 0 +#endif + +// A function level attribute to disable checking for use of uninitialized +// memory when built with MemorySanitizer. +#if defined(__clang__) +# if __has_feature(memory_sanitizer) +# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \ + __attribute__((no_sanitize_memory)) +# else +# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +# endif // __has_feature(memory_sanitizer) +#else +# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +#endif // __clang__ + +// A function level attribute to disable AddressSanitizer instrumentation. +#if defined(__clang__) +# if __has_feature(address_sanitizer) +# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ + __attribute__((no_sanitize_address)) +# else +# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +# endif // __has_feature(address_sanitizer) +#else +# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +#endif // __clang__ + +// A function level attribute to disable ThreadSanitizer instrumentation. +#if defined(__clang__) +# if __has_feature(thread_sanitizer) +# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \ + __attribute__((no_sanitize_thread)) +# else +# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +# endif // __has_feature(thread_sanitizer) +#else +# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +#endif // __clang__ + namespace testing { class Message; +#if defined(GTEST_TUPLE_NAMESPACE_) +// Import tuple and friends into the ::testing namespace. +// It is part of our interface, having them in ::testing allows us to change +// their types as needed. +using GTEST_TUPLE_NAMESPACE_::get; +using GTEST_TUPLE_NAMESPACE_::make_tuple; +using GTEST_TUPLE_NAMESPACE_::tuple; +using GTEST_TUPLE_NAMESPACE_::tuple_size; +using GTEST_TUPLE_NAMESPACE_::tuple_element; +#endif // defined(GTEST_TUPLE_NAMESPACE_) + namespace internal { -class String; +// A secret type that Google Test users don't know about. It has no +// definition on purpose. Therefore it's impossible to create a +// Secret object, which is what we want. +class Secret; // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time // expression is true. For example, you could use it to verify the // size of a static array: // -// GTEST_COMPILE_ASSERT_(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, -// content_type_names_incorrect_size); +// GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES, +// names_incorrect_size); // // or to make sure a struct is smaller than a certain size: // @@ -705,16 +1031,22 @@ class String; // the expression is false, most compilers will issue a warning/error // containing the name of the variable. +#if GTEST_LANG_CXX11 +# define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) +#else // !GTEST_LANG_CXX11 template <bool> -struct CompileAssert { + struct CompileAssert { }; -#define GTEST_COMPILE_ASSERT_(expr, msg) \ - typedef ::testing::internal::CompileAssert<(bool(expr))> \ - msg[bool(expr) ? 1 : -1] +# define GTEST_COMPILE_ASSERT_(expr, msg) \ + typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \ + msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ +#endif // !GTEST_LANG_CXX11 // Implementation details of GTEST_COMPILE_ASSERT_: // +// (In C++11, we simply use static_assert instead of the following) +// // - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 // elements (and thus is invalid) when the expression is false. // @@ -761,7 +1093,12 @@ template <typename T1, typename T2> struct StaticAssertTypeEqHelper; template <typename T> -struct StaticAssertTypeEqHelper<T, T> {}; +struct StaticAssertTypeEqHelper<T, T> { + enum { value = true }; +}; + +// Evaluates to the number of elements in 'array'. +#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) #if GTEST_HAS_GLOBAL_STRING typedef ::string string; @@ -809,6 +1146,12 @@ class scoped_ptr { ptr_ = p; } } + + friend void swap(scoped_ptr& a, scoped_ptr& b) { + using std::swap; + swap(a.ptr_, b.ptr_); + } + private: T* ptr_; @@ -871,10 +1214,9 @@ class GTEST_API_ RE { private: void Init(const char* regex); - // We use a const char* instead of a string, as Google Test may be used - // where string is not available. We also do not use Google Test's own - // String type here, in order to simplify dependencies between the - // files. + // We use a const char* instead of an std::string, as Google Test used to be + // used where std::string is not available. TODO(wan@google.com): change to + // std::string. const char* pattern_; bool is_valid_; @@ -933,13 +1275,18 @@ class GTEST_API_ GTestLog { GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); }; -#define GTEST_LOG_(severity) \ +#if !defined(GTEST_LOG_) + +# define GTEST_LOG_(severity) \ ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ __FILE__, __LINE__).GetStream() inline void LogToStderr() {} inline void FlushInfoLog() { fflush(NULL); } +#endif // !defined(GTEST_LOG_) + +#if !defined(GTEST_CHECK_) // INTERNAL IMPLEMENTATION - DO NOT USE. // // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition @@ -954,12 +1301,13 @@ inline void FlushInfoLog() { fflush(NULL); } // condition itself, plus additional message streamed into it, if any, // and then it aborts the program. It aborts the program irrespective of // whether it is built in the debug mode or not. -#define GTEST_CHECK_(condition) \ +# define GTEST_CHECK_(condition) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::IsTrue(condition)) \ ; \ else \ GTEST_LOG_(FATAL) << "Condition " #condition " failed. " +#endif // !defined(GTEST_CHECK_) // An all-mode assert to verify that the given POSIX-style function // call returns 0 (indicating success). Known limitation: this @@ -971,6 +1319,15 @@ inline void FlushInfoLog() { fflush(NULL); } GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ << gtest_error +#if GTEST_HAS_STD_MOVE_ +using std::move; +#else // GTEST_HAS_STD_MOVE_ +template <typename T> +const T& move(const T& t) { + return t; +} +#endif // GTEST_HAS_STD_MOVE_ + // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Use ImplicitCast_ as a safe version of static_cast for upcasting in @@ -1021,7 +1378,9 @@ inline To DownCast_(From* f) { // so we only accept pointers // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away // completely. + GTEST_INTENTIONAL_CONST_COND_PUSH_() if (false) { + GTEST_INTENTIONAL_CONST_COND_POP_() const To to = NULL; ::testing::internal::ImplicitCast_<From*>(to); } @@ -1042,6 +1401,11 @@ template <class Derived, class Base> Derived* CheckedDowncastToActualType(Base* base) { #if GTEST_HAS_RTTI GTEST_CHECK_(typeid(*base) == typeid(Derived)); +#endif + +#if GTEST_HAS_DOWNCAST_ + return ::down_cast<Derived*>(base); +#elif GTEST_HAS_RTTI return dynamic_cast<Derived*>(base); // NOLINT #else return static_cast<Derived*>(base); // Poor man's downcast. @@ -1057,30 +1421,39 @@ Derived* CheckedDowncastToActualType(Base* base) { // GetCapturedStderr - stops capturing stderr and returns the captured string. // GTEST_API_ void CaptureStdout(); -GTEST_API_ String GetCapturedStdout(); +GTEST_API_ std::string GetCapturedStdout(); GTEST_API_ void CaptureStderr(); -GTEST_API_ String GetCapturedStderr(); +GTEST_API_ std::string GetCapturedStderr(); #endif // GTEST_HAS_STREAM_REDIRECTION +// Returns a path to temporary directory. +GTEST_API_ std::string TempDir(); + +// Returns the size (in bytes) of a file. +GTEST_API_ size_t GetFileSize(FILE* file); + +// Reads the entire content of a file as a string. +GTEST_API_ std::string ReadEntireFile(FILE* file); + +// All command line arguments. +GTEST_API_ const ::std::vector<testing::internal::string>& GetArgvs(); #if GTEST_HAS_DEATH_TEST -// A copy of all command line arguments. Set by InitGoogleTest(). -extern ::std::vector<String> g_argvs; +const ::std::vector<testing::internal::string>& GetInjectableArgvs(); +void SetInjectableArgvs(const ::std::vector<testing::internal::string>* + new_argvs); -// GTEST_HAS_DEATH_TEST implies we have ::std::string. -const ::std::vector<String>& GetArgvs(); #endif // GTEST_HAS_DEATH_TEST // Defines synchronization primitives. - -#if GTEST_HAS_PTHREAD - -// Sleeps for (roughly) n milli-seconds. This function is only for -// testing Google Test's own constructs. Don't use it in user tests, -// either directly or indirectly. +#if GTEST_IS_THREADSAFE +# if GTEST_HAS_PTHREAD +// Sleeps for (roughly) n milliseconds. This function is only for testing +// Google Test's own constructs. Don't use it in user tests, either +// directly or indirectly. inline void SleepMilliseconds(int n) { const timespec time = { 0, // 0 seconds. @@ -1088,7 +1461,13 @@ inline void SleepMilliseconds(int n) { }; nanosleep(&time, NULL); } +# endif // GTEST_HAS_PTHREAD + +# if GTEST_HAS_NOTIFICATION_ +// Notification has already been imported into the namespace. +// Nothing to do here. +# elif GTEST_HAS_PTHREAD // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. @@ -1097,25 +1476,96 @@ inline void SleepMilliseconds(int n) { // use it in user tests, either directly or indirectly. class Notification { public: - Notification() : notified_(false) {} + Notification() : notified_(false) { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); + } + ~Notification() { + pthread_mutex_destroy(&mutex_); + } // Notifies all threads created with this notification to start. Must // be called from the controller thread. - void Notify() { notified_ = true; } + void Notify() { + pthread_mutex_lock(&mutex_); + notified_ = true; + pthread_mutex_unlock(&mutex_); + } // Blocks until the controller thread notifies. Must be called from a test // thread. void WaitForNotification() { - while(!notified_) { + for (;;) { + pthread_mutex_lock(&mutex_); + const bool notified = notified_; + pthread_mutex_unlock(&mutex_); + if (notified) + break; SleepMilliseconds(10); } } private: - volatile bool notified_; + pthread_mutex_t mutex_; + bool notified_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); +}; + +# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT + +GTEST_API_ void SleepMilliseconds(int n); + +// Provides leak-safe Windows kernel handle ownership. +// Used in death tests and in threading support. +class GTEST_API_ AutoHandle { + public: + // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to + // avoid including <windows.h> in this header file. Including <windows.h> is + // undesirable because it defines a lot of symbols and macros that tend to + // conflict with client code. This assumption is verified by + // WindowsTypesTest.HANDLEIsVoidStar. + typedef void* Handle; + AutoHandle(); + explicit AutoHandle(Handle handle); + + ~AutoHandle(); + + Handle Get() const; + void Reset(); + void Reset(Handle handle); + + private: + // Returns true iff the handle is a valid handle object that can be closed. + bool IsCloseable() const; + + Handle handle_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); +}; + +// Allows a controller thread to pause execution of newly created +// threads until notified. Instances of this class must be created +// and destroyed in the controller thread. +// +// This class is only for testing Google Test's own constructs. Do not +// use it in user tests, either directly or indirectly. +class GTEST_API_ Notification { + public: + Notification(); + void Notify(); + void WaitForNotification(); + + private: + AutoHandle event_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; +# endif // GTEST_HAS_NOTIFICATION_ + +// On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD +// defined, but we don't want to use MinGW's pthreads implementation, which +// has conformance problems with some versions of the POSIX standard. +# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam @@ -1124,7 +1574,7 @@ class Notification { // problem. class ThreadWithParamBase { public: - virtual ~ThreadWithParamBase(); + virtual ~ThreadWithParamBase() {} virtual void Run() = 0; }; @@ -1154,10 +1604,9 @@ extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { template <typename T> class ThreadWithParam : public ThreadWithParamBase { public: - typedef void (*UserThreadFunc)(T); + typedef void UserThreadFunc(T); - ThreadWithParam( - UserThreadFunc func, T param, Notification* thread_can_start) + ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : func_(func), param_(param), thread_can_start_(thread_can_start), @@ -1168,7 +1617,7 @@ class ThreadWithParam : public ThreadWithParamBase { GTEST_CHECK_POSIX_SUCCESS_( pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); } - ~ThreadWithParam() override { Join(); } + ~ThreadWithParam() { Join(); } void Join() { if (!finished_) { @@ -1177,14 +1626,14 @@ class ThreadWithParam : public ThreadWithParamBase { } } - void Run() override { + virtual void Run() { if (thread_can_start_ != NULL) thread_can_start_->WaitForNotification(); func_(param_); } private: - const UserThreadFunc func_; // User-supplied thread function. + UserThreadFunc* const func_; // User-supplied thread function. const T param_; // User-supplied parameter to the thread function. // When non-NULL, used to block execution until the controller thread // notifies. @@ -1194,47 +1643,316 @@ class ThreadWithParam : public ThreadWithParamBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; +# endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || + // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ + +# if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +// Mutex and ThreadLocal have already been imported into the namespace. +// Nothing to do here. + +# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT -// MutexBase and Mutex implement mutex on pthreads-based platforms. They -// are used in conjunction with class MutexLock: +// Mutex implements mutex on Windows platforms. It is used in conjunction +// with class MutexLock: // // Mutex mutex; // ... -// MutexLock lock(&mutex); // Acquires the mutex and releases it at the end -// // of the current scope. -// -// MutexBase implements behavior for both statically and dynamically -// allocated mutexes. Do not use MutexBase directly. Instead, write -// the following to define a static mutex: +// MutexLock lock(&mutex); // Acquires the mutex and releases it at the +// // end of the current scope. // +// A static Mutex *must* be defined or declared using one of the following +// macros: // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); +// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); +// +// (A non-static Mutex is defined/declared in the usual way). +class GTEST_API_ Mutex { + public: + enum MutexType { kStatic = 0, kDynamic = 1 }; + // We rely on kStaticMutex being 0 as it is to what the linker initializes + // type_ in static mutexes. critical_section_ will be initialized lazily + // in ThreadSafeLazyInit(). + enum StaticConstructorSelector { kStaticMutex = 0 }; + + // This constructor intentionally does nothing. It relies on type_ being + // statically initialized to 0 (effectively setting it to kStatic) and on + // ThreadSafeLazyInit() to lazily initialize the rest of the members. + explicit Mutex(StaticConstructorSelector /*dummy*/) {} + + Mutex(); + ~Mutex(); + + void Lock(); + + void Unlock(); + + // Does nothing if the current thread holds the mutex. Otherwise, crashes + // with high probability. + void AssertHeld(); + + private: + // Initializes owner_thread_id_ and critical_section_ in static mutexes. + void ThreadSafeLazyInit(); + + // Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx, + // we assume that 0 is an invalid value for thread IDs. + unsigned int owner_thread_id_; + + // For static mutexes, we rely on these members being initialized to zeros + // by the linker. + MutexType type_; + long critical_section_init_phase_; // NOLINT + _RTL_CRITICAL_SECTION* critical_section_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); +}; + +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::Mutex mutex + +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ + ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) + +// We cannot name this class MutexLock because the ctor declaration would +// conflict with a macro named MutexLock, which is defined on some +// platforms. That macro is used as a defensive measure to prevent against +// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than +// "MutexLock l(&mu)". Hence the typedef trick below. +class GTestMutexLock { + public: + explicit GTestMutexLock(Mutex* mutex) + : mutex_(mutex) { mutex_->Lock(); } + + ~GTestMutexLock() { mutex_->Unlock(); } + + private: + Mutex* const mutex_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); +}; + +typedef GTestMutexLock MutexLock; + +// Base class for ValueHolder<T>. Allows a caller to hold and delete a value +// without knowing its type. +class ThreadLocalValueHolderBase { + public: + virtual ~ThreadLocalValueHolderBase() {} +}; + +// Provides a way for a thread to send notifications to a ThreadLocal +// regardless of its parameter type. +class ThreadLocalBase { + public: + // Creates a new ValueHolder<T> object holding a default value passed to + // this ThreadLocal<T>'s constructor and returns it. It is the caller's + // responsibility not to call this when the ThreadLocal<T> instance already + // has a value on the current thread. + virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0; + + protected: + ThreadLocalBase() {} + virtual ~ThreadLocalBase() {} + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase); +}; + +// Maps a thread to a set of ThreadLocals that have values instantiated on that +// thread and notifies them when the thread exits. A ThreadLocal instance is +// expected to persist until all threads it has values on have terminated. +class GTEST_API_ ThreadLocalRegistry { + public: + // Registers thread_local_instance as having value on the current thread. + // Returns a value that can be used to identify the thread from other threads. + static ThreadLocalValueHolderBase* GetValueOnCurrentThread( + const ThreadLocalBase* thread_local_instance); + + // Invoked when a ThreadLocal instance is destroyed. + static void OnThreadLocalDestroyed( + const ThreadLocalBase* thread_local_instance); +}; + +class GTEST_API_ ThreadWithParamBase { + public: + void Join(); + + protected: + class Runnable { + public: + virtual ~Runnable() {} + virtual void Run() = 0; + }; + + ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start); + virtual ~ThreadWithParamBase(); + + private: + AutoHandle thread_; +}; + +// Helper class for testing Google Test's multi-threading constructs. +template <typename T> +class ThreadWithParam : public ThreadWithParamBase { + public: + typedef void UserThreadFunc(T); + + ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) + : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) { + } + virtual ~ThreadWithParam() {} + + private: + class RunnableImpl : public Runnable { + public: + RunnableImpl(UserThreadFunc* func, T param) + : func_(func), + param_(param) { + } + virtual ~RunnableImpl() {} + virtual void Run() { + func_(param_); + } + + private: + UserThreadFunc* const func_; + const T param_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl); + }; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); +}; + +// Implements thread-local storage on Windows systems. +// +// // Thread 1 +// ThreadLocal<int> tl(100); // 100 is the default value for each thread. // -// You can forward declare a static mutex like this: +// // Thread 2 +// tl.set(150); // Changes the value for thread 2 only. +// EXPECT_EQ(150, tl.get()); // -// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); +// // Thread 1 +// EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. +// tl.set(200); +// EXPECT_EQ(200, tl.get()); +// +// The template type argument T must have a public copy constructor. +// In addition, the default ThreadLocal constructor requires T to have +// a public default constructor. // -// To create a dynamic mutex, just define an object of type Mutex. +// The users of a TheadLocal instance have to make sure that all but one +// threads (including the main one) using that instance have exited before +// destroying it. Otherwise, the per-thread objects managed for them by the +// ThreadLocal instance are not guaranteed to be destroyed on all platforms. +// +// Google Test only uses global ThreadLocal objects. That means they +// will die after main() has returned. Therefore, no per-thread +// object managed by Google Test will be leaked as long as all threads +// using Google Test have exited when main() returns. +template <typename T> +class ThreadLocal : public ThreadLocalBase { + public: + ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {} + explicit ThreadLocal(const T& value) + : default_factory_(new InstanceValueHolderFactory(value)) {} + + ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); } + + T* pointer() { return GetOrCreateValue(); } + const T* pointer() const { return GetOrCreateValue(); } + const T& get() const { return *pointer(); } + void set(const T& value) { *pointer() = value; } + + private: + // Holds a value of T. Can be deleted via its base class without the caller + // knowing the type of T. + class ValueHolder : public ThreadLocalValueHolderBase { + public: + ValueHolder() : value_() {} + explicit ValueHolder(const T& value) : value_(value) {} + + T* pointer() { return &value_; } + + private: + T value_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); + }; + + + T* GetOrCreateValue() const { + return static_cast<ValueHolder*>( + ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); + } + + virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { + return default_factory_->MakeNewHolder(); + } + + class ValueHolderFactory { + public: + ValueHolderFactory() {} + virtual ~ValueHolderFactory() {} + virtual ValueHolder* MakeNewHolder() const = 0; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); + }; + + class DefaultValueHolderFactory : public ValueHolderFactory { + public: + DefaultValueHolderFactory() {} + virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); + }; + + class InstanceValueHolderFactory : public ValueHolderFactory { + public: + explicit InstanceValueHolderFactory(const T& value) : value_(value) {} + virtual ValueHolder* MakeNewHolder() const { + return new ValueHolder(value_); + } + + private: + const T value_; // The value for each thread. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); + }; + + scoped_ptr<ValueHolderFactory> default_factory_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); +}; + +# elif GTEST_HAS_PTHREAD + +// MutexBase and Mutex implement mutex on pthreads-based platforms. class MutexBase { public: // Acquires this mutex. void Lock() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); owner_ = pthread_self(); + has_owner_ = true; } // Releases this mutex. void Unlock() { - // We don't protect writing to owner_ here, as it's the caller's - // responsibility to ensure that the current thread holds the + // Since the lock is being released the owner_ field should no longer be + // considered valid. We don't protect writing to has_owner_ here, as it's + // the caller's responsibility to ensure that the current thread holds the // mutex when this is called. - owner_ = 0; + has_owner_ = false; GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld() const { - GTEST_CHECK_(owner_ == pthread_self()) + GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self())) << "The current thread is not holding the mutex @" << this; } @@ -1245,16 +1963,23 @@ class MutexBase { // have to be public. public: pthread_mutex_t mutex_; // The underlying pthread mutex. - pthread_t owner_; // The thread holding the mutex; 0 means no one holds it. + // has_owner_ indicates whether the owner_ field below contains a valid thread + // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All + // accesses to the owner_ field should be protected by a check of this field. + // An alternative might be to memset() owner_ to all zeros, but there's no + // guarantee that a zero'd pthread_t is necessarily invalid or even different + // from pthread_self(). + bool has_owner_; + pthread_t owner_; // The thread holding the mutex. }; // Forward-declares a static mutex. -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::MutexBase mutex +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::MutexBase mutex // Defines and statically (i.e. at link time) initializes a static mutex. -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ - ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, 0 } +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ + ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false, pthread_t() } // The Mutex class can only be used for mutexes created at runtime. It // shares its API with MutexBase otherwise. @@ -1262,7 +1987,7 @@ class Mutex : public MutexBase { public: Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); - owner_ = 0; + has_owner_ = false; } ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); @@ -1272,9 +1997,11 @@ class Mutex : public MutexBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; -// We cannot name this class MutexLock as the ctor declaration would +// We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some -// platforms. Hence the typedef trick below. +// platforms. That macro is used as a defensive measure to prevent against +// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than +// "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(MutexBase* mutex) @@ -1298,7 +2025,7 @@ typedef GTestMutexLock MutexLock; // ThreadLocalValueHolderBase. class ThreadLocalValueHolderBase { public: - virtual ~ThreadLocalValueHolderBase(); + virtual ~ThreadLocalValueHolderBase() {} }; // Called by pthread to delete thread-local data stored by @@ -1308,41 +2035,14 @@ extern "C" inline void DeleteThreadLocalValue(void* value_holder) { } // Implements thread-local storage on pthreads-based systems. -// -// // Thread 1 -// ThreadLocal<int> tl(100); // 100 is the default value for each thread. -// -// // Thread 2 -// tl.set(150); // Changes the value for thread 2 only. -// EXPECT_EQ(150, tl.get()); -// -// // Thread 1 -// EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. -// tl.set(200); -// EXPECT_EQ(200, tl.get()); -// -// The template type argument T must have a public copy constructor. -// In addition, the default ThreadLocal constructor requires T to have -// a public default constructor. -// -// An object managed for a thread by a ThreadLocal instance is deleted -// when the thread exits. Or, if the ThreadLocal instance dies in -// that thread, when the ThreadLocal dies. It's the user's -// responsibility to ensure that all other threads using a ThreadLocal -// have exited when it dies, or the per-thread objects for those -// threads will not be deleted. -// -// Google Test only uses global ThreadLocal objects. That means they -// will die after main() has returned. Therefore, no per-thread -// object managed by Google Test will be leaked as long as all threads -// using Google Test have exited when main() returns. template <typename T> class ThreadLocal { public: - ThreadLocal() : key_(CreateKey()), - default_() {} - explicit ThreadLocal(const T& value) : key_(CreateKey()), - default_(value) {} + ThreadLocal() + : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} + explicit ThreadLocal(const T& value) + : key_(CreateKey()), + default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { // Destroys the managed object for the current thread, if any. @@ -1362,6 +2062,7 @@ class ThreadLocal { // Holds a value of type T. class ValueHolder : public ThreadLocalValueHolderBase { public: + ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } @@ -1387,22 +2088,54 @@ class ThreadLocal { return CheckedDowncastToActualType<ValueHolder>(holder)->pointer(); } - ValueHolder* const new_holder = new ValueHolder(default_); + ValueHolder* const new_holder = default_factory_->MakeNewHolder(); ThreadLocalValueHolderBase* const holder_base = new_holder; GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); return new_holder->pointer(); } + class ValueHolderFactory { + public: + ValueHolderFactory() {} + virtual ~ValueHolderFactory() {} + virtual ValueHolder* MakeNewHolder() const = 0; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); + }; + + class DefaultValueHolderFactory : public ValueHolderFactory { + public: + DefaultValueHolderFactory() {} + virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); + }; + + class InstanceValueHolderFactory : public ValueHolderFactory { + public: + explicit InstanceValueHolderFactory(const T& value) : value_(value) {} + virtual ValueHolder* MakeNewHolder() const { + return new ValueHolder(value_); + } + + private: + const T value_; // The value for each thread. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); + }; + // A key pthreads uses for looking up per-thread values. const pthread_key_t key_; - const T default_; // The default value for each thread. + scoped_ptr<ValueHolderFactory> default_factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; -# define GTEST_IS_THREADSAFE 1 +# endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ -#else // GTEST_HAS_PTHREAD +#else // GTEST_IS_THREADSAFE // A dummy implementation of synchronization primitives (mutex, lock, // and thread-local variable). Necessary for compiling Google Test where @@ -1412,6 +2145,8 @@ class ThreadLocal { class Mutex { public: Mutex() {} + void Lock() {} + void Unlock() {} void AssertHeld() const {} }; @@ -1420,6 +2155,11 @@ class Mutex { # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex +// We cannot name this class MutexLock because the ctor declaration would +// conflict with a macro named MutexLock, which is defined on some +// platforms. That macro is used as a defensive measure to prevent against +// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than +// "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex*) {} // NOLINT @@ -1440,11 +2180,7 @@ class ThreadLocal { T value_; }; -// The above synchronization primitives have dummy implementations. -// Therefore Google Test is not thread-safe. -# define GTEST_IS_THREADSAFE 0 - -#endif // GTEST_HAS_PTHREAD +#endif // GTEST_IS_THREADSAFE // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. @@ -1542,6 +2278,10 @@ inline bool IsUpper(char ch) { inline bool IsXDigit(char ch) { return isxdigit(static_cast<unsigned char>(ch)) != 0; } +inline bool IsXDigit(wchar_t ch) { + const unsigned char low_byte = static_cast<unsigned char>(ch); + return ch == low_byte && isxdigit(low_byte) != 0; +} inline char ToLower(char ch) { return static_cast<char>(tolower(static_cast<unsigned char>(ch))); @@ -1550,6 +2290,13 @@ inline char ToUpper(char ch) { return static_cast<char>(toupper(static_cast<unsigned char>(ch))); } +inline std::string StripTrailingSpaces(std::string str) { + std::string::iterator it = str.end(); + while (it != str.begin() && IsSpace(*--it)) + it = str.erase(it); + return str; +} + // The testing::internal::posix namespace holds wrappers for common // POSIX functions. These wrappers hide the differences between // Windows/MSVC and POSIX systems. Since some compilers define these @@ -1613,11 +2360,7 @@ inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } // Functions deprecated by MSVC 8.0. -#ifdef _MSC_VER -// Temporarily disable warning 4996 (deprecated function). -# pragma warning(push) -# pragma warning(disable:4996) -#endif +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) inline const char* StrNCpy(char* dest, const char* src, size_t n) { return strncpy(dest, src, n); @@ -1627,7 +2370,7 @@ inline const char* StrNCpy(char* dest, const char* src, size_t n) { // StrError() aren't needed on Windows CE at this time and thus not // defined there. -#if !GTEST_OS_WINDOWS_MOBILE +#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT inline int ChDir(const char* dir) { return chdir(dir); } #endif inline FILE* FOpen(const char* path, const char* mode) { @@ -1651,8 +2394,9 @@ inline int Close(int fd) { return close(fd); } inline const char* StrError(int errnum) { return strerror(errnum); } #endif inline const char* GetEnv(const char* name) { -#if GTEST_OS_WINDOWS_MOBILE +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE | GTEST_OS_WINDOWS_RT // We are on Windows CE, which has no environment variables. + static_cast<void>(name); // To prevent 'unused argument' warning. return NULL; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) // Environment variables which we programmatically clear will be set to the @@ -1664,9 +2408,7 @@ inline const char* GetEnv(const char* name) { #endif } -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif +GTEST_DISABLE_MSC_WARNINGS_POP_() #if GTEST_OS_WINDOWS_MOBILE // Windows CE has no C library. The abort() function is used in @@ -1679,6 +2421,23 @@ inline void Abort() { abort(); } } // namespace posix +// MSVC "deprecates" snprintf and issues warnings wherever it is used. In +// order to avoid these warnings, we need to use _snprintf or _snprintf_s on +// MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate +// function in order to achieve that. We use macro definition here because +// snprintf is a variadic function. +#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE +// MSVC 2005 and above support variadic macros. +# define GTEST_SNPRINTF_(buffer, size, format, ...) \ + _snprintf_s(buffer, size, size, format, __VA_ARGS__) +#elif defined(_MSC_VER) +// Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't +// complain about _snprintf. +# define GTEST_SNPRINTF_ _snprintf +#else +# define GTEST_SNPRINTF_ snprintf +#endif + // The maximum number a BiggestInt can represent. This definition // works no matter BiggestInt is represented in one's complement or // two's complement. @@ -1731,7 +2490,6 @@ class TypeWithSize<4> { template <> class TypeWithSize<8> { public: - #if GTEST_OS_WINDOWS typedef __int64 Int; typedef unsigned __int64 UInt; @@ -1751,14 +2509,23 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Utilities for command line flags and environment variables. // Macro for referencing flags. -#define GTEST_FLAG(name) FLAGS_gtest_##name +#if !defined(GTEST_FLAG) +# define GTEST_FLAG(name) FLAGS_gtest_##name +#endif // !defined(GTEST_FLAG) + +#if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) +# define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 +#endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) + +#if !defined(GTEST_DECLARE_bool_) +# define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver // Macros for declaring flags. -#define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) -#define GTEST_DECLARE_int32_(name) \ +# define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) +# define GTEST_DECLARE_int32_(name) \ GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) #define GTEST_DECLARE_string_(name) \ - GTEST_API_ extern ::testing::internal::String GTEST_FLAG(name) + GTEST_API_ extern ::std::string GTEST_FLAG(name) // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ @@ -1766,7 +2533,15 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. #define GTEST_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) #define GTEST_DEFINE_string_(name, default_val, doc) \ - GTEST_API_ ::testing::internal::String GTEST_FLAG(name) = (default_val) + GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) + +#endif // !defined(GTEST_DECLARE_bool_) + +// Thread annotations +#if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) +# define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) +# define GTEST_LOCK_EXCLUDED_(locks) +#endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) // Parses 'str' for a 32-bit signed integer. If successful, writes the result // to *value and returns true; otherwise leaves *value unchanged and returns @@ -1780,7 +2555,7 @@ bool ParseInt32(const Message& src_text, const char* str, Int32* value); // corresponding to the given Google Test flag. bool BoolFromGTestEnv(const char* flag, bool default_val); GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); -const char* StringFromGTestEnv(const char* flag, const char* default_val); +std::string StringFromGTestEnv(const char* flag, const char* default_val); } // namespace internal } // namespace testing diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-string.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-string.h index dc3a07be880..97f1a7fdd2c 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-string.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-string.h @@ -47,50 +47,18 @@ #endif #include <string.h> -#include "gtest/internal/gtest-port.h" - #include <string> +#include "gtest/internal/gtest-port.h" + namespace testing { namespace internal { -// String - a UTF-8 string class. -// -// For historic reasons, we don't use std::string. -// -// TODO(wan@google.com): replace this class with std::string or -// implement it in terms of the latter. -// -// Note that String can represent both NULL and the empty string, -// while std::string cannot represent NULL. -// -// NULL and the empty string are considered different. NULL is less -// than anything (including the empty string) except itself. -// -// This class only provides minimum functionality necessary for -// implementing Google Test. We do not intend to implement a full-fledged -// string class here. -// -// Since the purpose of this class is to provide a substitute for -// std::string on platforms where it cannot be used, we define a copy -// constructor and assignment operators such that we don't need -// conditional compilation in a lot of places. -// -// In order to make the representation efficient, the d'tor of String -// is not virtual. Therefore DO NOT INHERIT FROM String. +// String - an abstract class holding static string utilities. class GTEST_API_ String { public: // Static utility methods - // Returns the input enclosed in double quotes if it's not NULL; - // otherwise returns "(null)". For example, "\"Hello\"" is returned - // for input "Hello". - // - // This is useful for printing a C string in the syntax of a literal. - // - // Known issue: escape sequences are not handled yet. - static String ShowCStringQuoted(const char* c_str); - // Clones a 0-terminated C string, allocating memory using new. The // caller is responsible for deleting the return value using // delete[]. Returns the cloned string, or NULL if the input is @@ -137,11 +105,7 @@ class GTEST_API_ String { // NULL will be converted to "(null)". If an error occurred during // the conversion, "(failed to convert from wide string)" is // returned. - static String ShowWideCString(const wchar_t* wide_c_str); - - // Similar to ShowWideCString(), except that this function encloses - // the converted string in double quotes. - static String ShowWideCStringQuoted(const wchar_t* wide_c_str); + static std::string ShowWideCString(const wchar_t* wide_c_str); // Compares two wide C strings. Returns true iff they have the same // content. @@ -175,174 +139,27 @@ class GTEST_API_ String { static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); - // Formats a list of arguments to a String, using the same format - // spec string as for printf. - // - // We do not use the StringPrintf class as it is not universally - // available. - // - // The result is limited to 4096 characters (including the tailing - // 0). If 4096 characters are not enough to format the input, - // "<buffer exceeded>" is returned. - static String Format(const char* format, ...); - - // C'tors - - // The default c'tor constructs a NULL string. - String() : c_str_(NULL), length_(0) {} - - // Constructs a String by cloning a 0-terminated C string. - String(const char* a_c_str) { // NOLINT - if (a_c_str == NULL) { - c_str_ = NULL; - length_ = 0; - } else { - ConstructNonNull(a_c_str, strlen(a_c_str)); - } - } + // Returns true iff the given string ends with the given suffix, ignoring + // case. Any string is considered to end with an empty suffix. + static bool EndsWithCaseInsensitive( + const std::string& str, const std::string& suffix); - // Constructs a String by copying a given number of chars from a - // buffer. E.g. String("hello", 3) creates the string "hel", - // String("a\0bcd", 4) creates "a\0bc", String(NULL, 0) creates "", - // and String(NULL, 1) results in access violation. - String(const char* buffer, size_t a_length) { - ConstructNonNull(buffer, a_length); - } + // Formats an int value as "%02d". + static std::string FormatIntWidth2(int value); // "%02d" for width == 2 - // The copy c'tor creates a new copy of the string. The two - // String objects do not share content. - String(const String& str) : c_str_(NULL), length_(0) { *this = str; } + // Formats an int value as "%X". + static std::string FormatHexInt(int value); - // D'tor. String is intended to be a final class, so the d'tor - // doesn't need to be virtual. - ~String() { delete[] c_str_; } - - // Allows a String to be implicitly converted to an ::std::string or - // ::string, and vice versa. Converting a String containing a NULL - // pointer to ::std::string or ::string is undefined behavior. - // Converting a ::std::string or ::string containing an embedded NUL - // character to a String will result in the prefix up to the first - // NUL character. - String(const ::std::string& str) { - ConstructNonNull(str.c_str(), str.length()); - } - - operator ::std::string() const { return ::std::string(c_str(), length()); } - -#if GTEST_HAS_GLOBAL_STRING - String(const ::string& str) { - ConstructNonNull(str.c_str(), str.length()); - } - - operator ::string() const { return ::string(c_str(), length()); } -#endif // GTEST_HAS_GLOBAL_STRING - - // Returns true iff this is an empty string (i.e. ""). - bool empty() const { return (c_str() != NULL) && (length() == 0); } - - // Compares this with another String. - // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 - // if this is greater than rhs. - int Compare(const String& rhs) const; - - // Returns true iff this String equals the given C string. A NULL - // string and a non-NULL string are considered not equal. - bool operator==(const char* a_c_str) const { return Compare(a_c_str) == 0; } - - // Returns true iff this String is less than the given String. A - // NULL string is considered less than "". - bool operator<(const String& rhs) const { return Compare(rhs) < 0; } - - // Returns true iff this String doesn't equal the given C string. A NULL - // string and a non-NULL string are considered not equal. - bool operator!=(const char* a_c_str) const { return !(*this == a_c_str); } - - // Returns true iff this String ends with the given suffix. *Any* - // String is considered to end with a NULL or empty suffix. - bool EndsWith(const char* suffix) const; - - // Returns true iff this String ends with the given suffix, not considering - // case. Any String is considered to end with a NULL or empty suffix. - bool EndsWithCaseInsensitive(const char* suffix) const; - - // Returns the length of the encapsulated string, or 0 if the - // string is NULL. - size_t length() const { return length_; } - - // Gets the 0-terminated C string this String object represents. - // The String object still owns the string. Therefore the caller - // should NOT delete the return value. - const char* c_str() const { return c_str_; } - - // Assigns a C string to this object. Self-assignment works. - const String& operator=(const char* a_c_str) { - return *this = String(a_c_str); - } - - // Assigns a String object to this object. Self-assignment works. - const String& operator=(const String& rhs) { - if (this != &rhs) { - delete[] c_str_; - if (rhs.c_str() == NULL) { - c_str_ = NULL; - length_ = 0; - } else { - ConstructNonNull(rhs.c_str(), rhs.length()); - } - } - - return *this; - } + // Formats a byte as "%02X". + static std::string FormatByte(unsigned char value); private: - // Constructs a non-NULL String from the given content. This - // function can only be called when c_str_ has not been allocated. - // ConstructNonNull(NULL, 0) results in an empty string (""). - // ConstructNonNull(NULL, non_zero) is undefined behavior. - void ConstructNonNull(const char* buffer, size_t a_length) { - char* const str = new char[a_length + 1]; - memcpy(str, buffer, a_length); - str[a_length] = '\0'; - c_str_ = str; - length_ = a_length; - } - - const char* c_str_; - size_t length_; + String(); // Not meant to be instantiated. }; // class String -// Streams a String to an ostream. Each '\0' character in the String -// is replaced with "\\0". -inline ::std::ostream& operator<<(::std::ostream& os, const String& str) { - if (str.c_str() == NULL) { - os << "(null)"; - } else { - const char* const c_str = str.c_str(); - for (size_t i = 0; i != str.length(); i++) { - if (c_str[i] == '\0') { - os << "\\0"; - } else { - os << c_str[i]; - } - } - } - return os; -} - -// Gets the content of the stringstream's buffer as a String. Each '\0' +// Gets the content of the stringstream's buffer as an std::string. Each '\0' // character in the buffer is replaced with "\\0". -GTEST_API_ String StringStreamToString(::std::stringstream* stream); - -// Converts a streamable value to a String. A NULL pointer is -// converted to "(null)". When the input value is a ::string, -// ::std::string, ::wstring, or ::std::wstring object, each NUL -// character in it is replaced with "\\0". - -// Declared here but defined in gtest.h, so that it has access -// to the definition of the Message class, required by the ARM -// compiler. -template <typename T> -String StreamableToString(const T& streamable); +GTEST_API_ std::string StringStreamToString(::std::stringstream* stream); } // namespace internal } // namespace testing diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-tuple.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-tuple.h index d1af50e1883..e9b405340a8 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-tuple.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-tuple.h @@ -1,4 +1,6 @@ -// This file was GENERATED by a script. DO NOT EDIT BY HAND!!! +// This file was GENERATED by command: +// pump.py gtest-tuple.h.pump +// DO NOT EDIT BY HAND!!! // Copyright 2009 Google Inc. // All Rights Reserved. @@ -51,6 +53,14 @@ private: #endif +// Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that conflict +// with our own definitions. Therefore using our own tuple does not work on +// those compilers. +#if defined(_MSC_VER) && _MSC_VER >= 1600 /* 1600 is Visual Studio 2010 */ +# error "gtest's tuple doesn't compile on Visual Studio 2010 or later. \ +GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers." +#endif + // GTEST_n_TUPLE_(T) is the type of an n-tuple. #define GTEST_0_TUPLE_(T) tuple<> #define GTEST_1_TUPLE_(T) tuple<T##0, void, void, void, void, void, void, \ @@ -140,34 +150,54 @@ template <bool kIndexValid, int kIndex, class Tuple> struct TupleElement; template <GTEST_10_TYPENAMES_(T)> -struct TupleElement<true, 0, GTEST_10_TUPLE_(T)> { typedef T0 type; }; +struct TupleElement<true, 0, GTEST_10_TUPLE_(T) > { + typedef T0 type; +}; template <GTEST_10_TYPENAMES_(T)> -struct TupleElement<true, 1, GTEST_10_TUPLE_(T)> { typedef T1 type; }; +struct TupleElement<true, 1, GTEST_10_TUPLE_(T) > { + typedef T1 type; +}; template <GTEST_10_TYPENAMES_(T)> -struct TupleElement<true, 2, GTEST_10_TUPLE_(T)> { typedef T2 type; }; +struct TupleElement<true, 2, GTEST_10_TUPLE_(T) > { + typedef T2 type; +}; template <GTEST_10_TYPENAMES_(T)> -struct TupleElement<true, 3, GTEST_10_TUPLE_(T)> { typedef T3 type; }; +struct TupleElement<true, 3, GTEST_10_TUPLE_(T) > { + typedef T3 type; +}; template <GTEST_10_TYPENAMES_(T)> -struct TupleElement<true, 4, GTEST_10_TUPLE_(T)> { typedef T4 type; }; +struct TupleElement<true, 4, GTEST_10_TUPLE_(T) > { + typedef T4 type; +}; template <GTEST_10_TYPENAMES_(T)> -struct TupleElement<true, 5, GTEST_10_TUPLE_(T)> { typedef T5 type; }; +struct TupleElement<true, 5, GTEST_10_TUPLE_(T) > { + typedef T5 type; +}; template <GTEST_10_TYPENAMES_(T)> -struct TupleElement<true, 6, GTEST_10_TUPLE_(T)> { typedef T6 type; }; +struct TupleElement<true, 6, GTEST_10_TUPLE_(T) > { + typedef T6 type; +}; template <GTEST_10_TYPENAMES_(T)> -struct TupleElement<true, 7, GTEST_10_TUPLE_(T)> { typedef T7 type; }; +struct TupleElement<true, 7, GTEST_10_TUPLE_(T) > { + typedef T7 type; +}; template <GTEST_10_TYPENAMES_(T)> -struct TupleElement<true, 8, GTEST_10_TUPLE_(T)> { typedef T8 type; }; +struct TupleElement<true, 8, GTEST_10_TUPLE_(T) > { + typedef T8 type; +}; template <GTEST_10_TYPENAMES_(T)> -struct TupleElement<true, 9, GTEST_10_TUPLE_(T)> { typedef T9 type; }; +struct TupleElement<true, 9, GTEST_10_TUPLE_(T) > { + typedef T9 type; +}; } // namespace gtest_internal @@ -708,37 +738,59 @@ inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, template <typename Tuple> struct tuple_size; template <GTEST_0_TYPENAMES_(T)> -struct tuple_size<GTEST_0_TUPLE_(T)> { static const int value = 0; }; +struct tuple_size<GTEST_0_TUPLE_(T) > { + static const int value = 0; +}; template <GTEST_1_TYPENAMES_(T)> -struct tuple_size<GTEST_1_TUPLE_(T)> { static const int value = 1; }; +struct tuple_size<GTEST_1_TUPLE_(T) > { + static const int value = 1; +}; template <GTEST_2_TYPENAMES_(T)> -struct tuple_size<GTEST_2_TUPLE_(T)> { static const int value = 2; }; +struct tuple_size<GTEST_2_TUPLE_(T) > { + static const int value = 2; +}; template <GTEST_3_TYPENAMES_(T)> -struct tuple_size<GTEST_3_TUPLE_(T)> { static const int value = 3; }; +struct tuple_size<GTEST_3_TUPLE_(T) > { + static const int value = 3; +}; template <GTEST_4_TYPENAMES_(T)> -struct tuple_size<GTEST_4_TUPLE_(T)> { static const int value = 4; }; +struct tuple_size<GTEST_4_TUPLE_(T) > { + static const int value = 4; +}; template <GTEST_5_TYPENAMES_(T)> -struct tuple_size<GTEST_5_TUPLE_(T)> { static const int value = 5; }; +struct tuple_size<GTEST_5_TUPLE_(T) > { + static const int value = 5; +}; template <GTEST_6_TYPENAMES_(T)> -struct tuple_size<GTEST_6_TUPLE_(T)> { static const int value = 6; }; +struct tuple_size<GTEST_6_TUPLE_(T) > { + static const int value = 6; +}; template <GTEST_7_TYPENAMES_(T)> -struct tuple_size<GTEST_7_TUPLE_(T)> { static const int value = 7; }; +struct tuple_size<GTEST_7_TUPLE_(T) > { + static const int value = 7; +}; template <GTEST_8_TYPENAMES_(T)> -struct tuple_size<GTEST_8_TUPLE_(T)> { static const int value = 8; }; +struct tuple_size<GTEST_8_TUPLE_(T) > { + static const int value = 8; +}; template <GTEST_9_TYPENAMES_(T)> -struct tuple_size<GTEST_9_TUPLE_(T)> { static const int value = 9; }; +struct tuple_size<GTEST_9_TUPLE_(T) > { + static const int value = 9; +}; template <GTEST_10_TYPENAMES_(T)> -struct tuple_size<GTEST_10_TUPLE_(T)> { static const int value = 10; }; +struct tuple_size<GTEST_10_TUPLE_(T) > { + static const int value = 10; +}; template <int k, class Tuple> struct tuple_element { @@ -922,8 +974,8 @@ template <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)> inline bool operator==(const GTEST_10_TUPLE_(T)& t, const GTEST_10_TUPLE_(U)& u) { return gtest_internal::SameSizeTuplePrefixComparator< - tuple_size<GTEST_10_TUPLE_(T)>::value, - tuple_size<GTEST_10_TUPLE_(U)>::value>::Eq(t, u); + tuple_size<GTEST_10_TUPLE_(T) >::value, + tuple_size<GTEST_10_TUPLE_(U) >::value>::Eq(t, u); } template <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)> diff --git a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-type-util.h b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-type-util.h index b7b01b0948c..e46f7cfcb48 100644 --- a/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-type-util.h +++ b/gnu/llvm/utils/unittest/googletest/include/gtest/internal/gtest-type-util.h @@ -45,15 +45,14 @@ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #include "gtest/internal/gtest-port.h" -#include "gtest/internal/gtest-string.h" // #ifdef __GNUC__ is too general here. It is possible to use gcc without using // libstdc++ (which is where cxxabi.h comes from). -# ifdef __GLIBCXX__ +# if GTEST_HAS_CXXABI_H_ # include <cxxabi.h> # elif defined(__HP_aCC) # include <acxx_demangle.h> -# endif // __GLIBCXX__ +# endif // GTEST_HASH_CXXABI_H_ namespace testing { namespace internal { @@ -62,24 +61,24 @@ namespace internal { // NB: This function is also used in Google Mock, so don't move it inside of // the typed-test-only section below. template <typename T> -String GetTypeName() { +std::string GetTypeName() { # if GTEST_HAS_RTTI const char* const name = typeid(T).name(); -# if defined(__GLIBCXX__) || defined(__HP_aCC) +# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) int status = 0; // gcc's implementation of typeid(T).name() mangles the type name, // so we have to demangle it. -# ifdef __GLIBCXX__ +# if GTEST_HAS_CXXABI_H_ using abi::__cxa_demangle; -# endif // __GLIBCXX__ +# endif // GTEST_HAS_CXXABI_H_ char* const readable_name = __cxa_demangle(name, 0, 0, &status); - const String name_str(status == 0 ? readable_name : name); + const std::string name_str(status == 0 ? readable_name : name); free(readable_name); return name_str; # else return name; -# endif // __GLIBCXX__ || __HP_aCC +# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC # else @@ -3300,7 +3299,9 @@ struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, // INSTANTIATE_TYPED_TEST_CASE_P(). template <typename T> -struct TypeList { typedef Types1<T> type; }; +struct TypeList { + typedef Types1<T> type; +}; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, diff --git a/gnu/llvm/utils/unittest/googletest/src/gtest-death-test.cc b/gnu/llvm/utils/unittest/googletest/src/gtest-death-test.cc index 47c1a15b820..a01a3698308 100644 --- a/gnu/llvm/utils/unittest/googletest/src/gtest-death-test.cc +++ b/gnu/llvm/utils/unittest/googletest/src/gtest-death-test.cc @@ -33,6 +33,7 @@ #include "gtest/gtest-death-test.h" #include "gtest/internal/gtest-port.h" +#include "gtest/internal/custom/gtest.h" #if GTEST_HAS_DEATH_TEST @@ -43,6 +44,11 @@ # include <errno.h> # include <fcntl.h> # include <limits.h> + +# if GTEST_OS_LINUX +# include <signal.h> +# endif // GTEST_OS_LINUX + # include <stdarg.h> # if GTEST_OS_WINDOWS @@ -52,6 +58,10 @@ # include <sys/wait.h> # endif // GTEST_OS_WINDOWS +# if GTEST_OS_QNX +# include <spawn.h> +# endif // GTEST_OS_QNX + #endif // GTEST_HAS_DEATH_TEST #include "gtest/gtest-message.h" @@ -59,9 +69,9 @@ // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. +// included, or there will be a compiler error. This trick exists to +// prevent the accidental inclusion of gtest-internal-inl.h in the +// user's code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ @@ -100,13 +110,44 @@ GTEST_DEFINE_string_( "Indicates the file, line number, temporal index of " "the single death test to run, and a file descriptor to " "which a success code may be sent, all separated by " - "colons. This flag is specified if and only if the current " + "the '|' characters. This flag is specified if and only if the current " "process is a sub-process launched for running a thread-safe " "death test. FOR INTERNAL USE ONLY."); } // namespace internal #if GTEST_HAS_DEATH_TEST +namespace internal { + +// Valid only for fast death tests. Indicates the code is running in the +// child process of a fast style death test. +# if !GTEST_OS_WINDOWS +static bool g_in_fast_death_test_child = false; +# endif + +// Returns a Boolean value indicating whether the caller is currently +// executing in the context of the death test child process. Tools such as +// Valgrind heap checkers may need this to modify their behavior in death +// tests. IMPORTANT: This is an internal utility. Using it may break the +// implementation of death tests. User code MUST NOT use it. +bool InDeathTestChild() { +# if GTEST_OS_WINDOWS + + // On Windows, death tests are thread-safe regardless of the value of the + // death_test_style flag. + return !GTEST_FLAG(internal_run_death_test).empty(); + +# else + + if (GTEST_FLAG(death_test_style) == "threadsafe") + return !GTEST_FLAG(internal_run_death_test).empty(); + else + return g_in_fast_death_test_child; +#endif +} + +} // namespace internal + // ExitedWithCode constructor. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { } @@ -131,6 +172,14 @@ KilledBySignal::KilledBySignal(int signum) : signum_(signum) { // KilledBySignal function-call operator. bool KilledBySignal::operator()(int exit_status) const { +# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) + { + bool result; + if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { + return result; + } + } +# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; } # endif // !GTEST_OS_WINDOWS @@ -141,7 +190,7 @@ namespace internal { // Generates a textual description of a given exit code, in the format // specified by wait(2). -static String ExitSummary(int exit_code) { +static std::string ExitSummary(int exit_code) { Message m; # if GTEST_OS_WINDOWS @@ -176,7 +225,7 @@ bool ExitedUnsuccessfully(int exit_status) { // one thread running, or cannot determine the number of threads, prior // to executing the given statement. It is the responsibility of the // caller not to pass a thread_count of 1. -static String DeathTestThreadWarning(size_t thread_count) { +static std::string DeathTestThreadWarning(size_t thread_count) { Message msg; msg << "Death tests use fork(), which is unsafe particularly" << " in a threaded context. For this test, " << GTEST_NAME_ << " "; @@ -210,7 +259,7 @@ enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; // message is propagated back to the parent process. Otherwise, the // message is simply printed to stderr. In either case, the program // then exits with status 1. -void DeathTestAbort(const String& message) { +void DeathTestAbort(const std::string& message) { // On a POSIX system, this function may be called from a threadsafe-style // death test child process, which operates on a very small stack. Use // the heap for any additional non-minuscule memory requirements. @@ -234,9 +283,10 @@ void DeathTestAbort(const String& message) { # define GTEST_DEATH_TEST_CHECK_(expression) \ do { \ if (!::testing::internal::IsTrue(expression)) { \ - DeathTestAbort(::testing::internal::String::Format( \ - "CHECK failed: File %s, line %d: %s", \ - __FILE__, __LINE__, #expression)); \ + DeathTestAbort( \ + ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + + ::testing::internal::StreamableToString(__LINE__) + ": " \ + + #expression); \ } \ } while (::testing::internal::AlwaysFalse()) @@ -254,15 +304,16 @@ void DeathTestAbort(const String& message) { gtest_retval = (expression); \ } while (gtest_retval == -1 && errno == EINTR); \ if (gtest_retval == -1) { \ - DeathTestAbort(::testing::internal::String::Format( \ - "CHECK failed: File %s, line %d: %s != -1", \ - __FILE__, __LINE__, #expression)); \ + DeathTestAbort( \ + ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + + ::testing::internal::StreamableToString(__LINE__) + ": " \ + + #expression + " != -1"); \ } \ } while (::testing::internal::AlwaysFalse()) // Returns the message describing the last system error in errno. -String GetLastErrnoDescription() { - return String(errno == 0 ? "" : posix::StrError(errno)); +std::string GetLastErrnoDescription() { + return errno == 0 ? "" : posix::StrError(errno); } // This is called from a death test parent process to read a failure @@ -300,9 +351,6 @@ DeathTest::DeathTest() { } } -// Pin the vtable to this file. -DeathTest::~DeathTest() {} - // Creates and returns a death test by dispatching to the current // death test factory. bool DeathTest::Create(const char* statement, const RE* regex, @@ -315,11 +363,11 @@ const char* DeathTest::LastMessage() { return last_death_test_message_.c_str(); } -void DeathTest::set_last_death_test_message(const String& message) { +void DeathTest::set_last_death_test_message(const std::string& message) { last_death_test_message_ = message; } -String DeathTest::last_death_test_message_; +std::string DeathTest::last_death_test_message_; // Provides cross platform implementation for some death functionality. class DeathTestImpl : public DeathTest { @@ -334,10 +382,10 @@ class DeathTestImpl : public DeathTest { write_fd_(-1) {} // read_fd_ is expected to be closed and cleared by a derived class. - ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } + ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } - void Abort(AbortReason reason) override; - bool Passed(bool status_ok) override; + void Abort(AbortReason reason); + virtual bool Passed(bool status_ok); const char* statement() const { return statement_; } const RE* regex() const { return regex_; } @@ -494,7 +542,7 @@ bool DeathTestImpl::Passed(bool status_ok) { if (!spawned()) return false; - const String error_message = GetCapturedStderr(); + const std::string error_message = GetCapturedStderr(); bool success = false; Message buffer; @@ -530,6 +578,7 @@ bool DeathTestImpl::Passed(bool status_ok) { } break; case IN_PROGRESS: + default: GTEST_LOG_(FATAL) << "DeathTest::Passed somehow called before conclusion of test"; } @@ -675,22 +724,19 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { FALSE, // The initial state is non-signalled. NULL)); // The even is unnamed. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); - const String filter_flag = String::Format("--%s%s=%s.%s", - GTEST_FLAG_PREFIX_, kFilterFlag, - info->test_case_name(), - info->name()); - const String internal_flag = String::Format( - "--%s%s=%s|%d|%d|%u|%Iu|%Iu", - GTEST_FLAG_PREFIX_, - kInternalRunDeathTestFlag, - file_, line_, - death_test_index, - static_cast<unsigned int>(::GetCurrentProcessId()), - // size_t has the same with as pointers on both 32-bit and 64-bit + const std::string filter_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + + info->test_case_name() + "." + info->name(); + const std::string internal_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + + "=" + file_ + "|" + StreamableToString(line_) + "|" + + StreamableToString(death_test_index) + "|" + + StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) + + // size_t has the same width as pointers on both 32-bit and 64-bit // Windows platforms. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. - reinterpret_cast<size_t>(write_handle), - reinterpret_cast<size_t>(event_handle_.Get())); + "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + + "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get())); char executable_path[_MAX_PATH + 1]; // NOLINT GTEST_DEATH_TEST_CHECK_( @@ -698,10 +744,9 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { executable_path, _MAX_PATH)); - String command_line = String::Format("%s %s \"%s\"", - ::GetCommandLineA(), - filter_flag.c_str(), - internal_flag.c_str()); + std::string command_line = + std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + + internal_flag + "\""; DeathTest::set_last_death_test_message(""); @@ -744,7 +789,7 @@ class ForkingDeathTest : public DeathTestImpl { ForkingDeathTest(const char* statement, const RE* regex); // All of these virtual functions are inherited from DeathTest. - int Wait() override; + virtual int Wait(); protected: void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } @@ -780,7 +825,7 @@ class NoExecDeathTest : public ForkingDeathTest { public: NoExecDeathTest(const char* a_statement, const RE* a_regex) : ForkingDeathTest(a_statement, a_regex) { } - TestRole AssumeRole() override; + virtual TestRole AssumeRole(); }; // The AssumeRole process for a fork-and-run death test. It implements a @@ -818,6 +863,7 @@ DeathTest::TestRole NoExecDeathTest::AssumeRole() { // Event forwarding to the listeners of event listener API mush be shut // down in death test subprocesses. GetUnitTestImpl()->listeners()->SuppressEventForwarding(); + g_in_fast_death_test_child = true; return EXECUTE_TEST; } else { GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); @@ -835,9 +881,18 @@ class ExecDeathTest : public ForkingDeathTest { ExecDeathTest(const char* a_statement, const RE* a_regex, const char* file, int line) : ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } - TestRole AssumeRole() override; - + virtual TestRole AssumeRole(); private: + static ::std::vector<testing::internal::string> + GetArgvsForDeathTestChildProcess() { + ::std::vector<testing::internal::string> args = GetInjectableArgvs(); +# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) + ::std::vector<testing::internal::string> extra_args = + GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); + args.insert(args.end(), extra_args.begin(), extra_args.end()); +# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) + return args; + } // The name of the file in which the death test is located. const char* const file_; // The line number on which the death test is located. @@ -872,6 +927,7 @@ class Arguments { char* const* Argv() { return &args_[0]; } + private: std::vector<char*> args_; }; @@ -897,6 +953,7 @@ extern "C" char** environ; inline char** GetEnviron() { return environ; } # endif // GTEST_OS_MAC +# if !GTEST_OS_QNX // The main function for a threadsafe-style death test child process. // This function is called in a clone()-ed process and thus must avoid // any potentially unsafe operations like malloc or libc functions. @@ -911,9 +968,8 @@ static int ExecDeathTestChildMain(void* child_arg) { UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { - DeathTestAbort(String::Format("chdir(\"%s\") failed: %s", - original_dir, - GetLastErrnoDescription().c_str())); + DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + + GetLastErrnoDescription()); return EXIT_FAILURE; } @@ -923,12 +979,12 @@ static int ExecDeathTestChildMain(void* child_arg) { // invoke the test program via a valid path that contains at least // one path separator. execve(args->argv[0], args->argv, GetEnviron()); - DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s", - args->argv[0], - original_dir, - GetLastErrnoDescription().c_str())); + DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + + original_dir + " failed: " + + GetLastErrnoDescription()); return EXIT_FAILURE; } +# endif // !GTEST_OS_QNX // Two utility routines that together determine the direction the stack // grows. @@ -939,25 +995,77 @@ static int ExecDeathTestChildMain(void* child_arg) { // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining // StackLowerThanAddress into StackGrowsDown, which then doesn't give // correct answer. -bool StackLowerThanAddress(const void* ptr) GTEST_NO_INLINE_; -bool StackLowerThanAddress(const void* ptr) { +void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_; +void StackLowerThanAddress(const void* ptr, bool* result) { int dummy; - return &dummy < ptr; + *result = (&dummy < ptr); } +// Make sure AddressSanitizer does not tamper with the stack here. +GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ bool StackGrowsDown() { int dummy; - return StackLowerThanAddress(&dummy); + bool result; + StackLowerThanAddress(&dummy, &result); + return result; } -// A threadsafe implementation of fork(2) for threadsafe-style death tests -// that uses clone(2). It dies with an error message if anything goes -// wrong. -static pid_t ExecDeathTestFork(char* const* argv, int close_fd) { +// Spawns a child process with the same executable as the current process in +// a thread-safe manner and instructs it to run the death test. The +// implementation uses fork(2) + exec. On systems where clone(2) is +// available, it is used instead, being slightly more thread-safe. On QNX, +// fork supports only single-threaded environments, so this function uses +// spawn(2) there instead. The function dies with an error message if +// anything goes wrong. +static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { ExecDeathTestArgs args = { argv, close_fd }; pid_t child_pid = -1; -# if GTEST_HAS_CLONE +# if GTEST_OS_QNX + // Obtains the current directory and sets it to be closed in the child + // process. + const int cwd_fd = open(".", O_RDONLY); + GTEST_DEATH_TEST_CHECK_(cwd_fd != -1); + GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC)); + // We need to execute the test program in the same environment where + // it was originally invoked. Therefore we change to the original + // working directory first. + const char* const original_dir = + UnitTest::GetInstance()->original_working_dir(); + // We can safely call chdir() as it's a direct system call. + if (chdir(original_dir) != 0) { + DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + + GetLastErrnoDescription()); + return EXIT_FAILURE; + } + + int fd_flags; + // Set close_fd to be closed after spawn. + GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); + GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, + fd_flags | FD_CLOEXEC)); + struct inheritance inherit = {0}; + // spawn is a system call. + child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron()); + // Restores the current working directory. + GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); + +# else // GTEST_OS_QNX +# if GTEST_OS_LINUX + // When a SIGPROF signal is received while fork() or clone() are executing, + // the process may hang. To avoid this, we ignore SIGPROF here and re-enable + // it after the call to fork()/clone() is complete. + struct sigaction saved_sigprof_action; + struct sigaction ignore_sigprof_action; + memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); + sigemptyset(&ignore_sigprof_action.sa_mask); + ignore_sigprof_action.sa_handler = SIG_IGN; + GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( + SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); +# endif // GTEST_OS_LINUX + +# if GTEST_HAS_CLONE const bool use_fork = GTEST_FLAG(death_test_use_fork); if (!use_fork) { @@ -967,21 +1075,37 @@ static pid_t ExecDeathTestFork(char* const* argv, int close_fd) { void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); + + // Maximum stack alignment in bytes: For a downward-growing stack, this + // amount is subtracted from size of the stack space to get an address + // that is within the stack space and is aligned on all systems we care + // about. As far as I know there is no ABI with stack alignment greater + // than 64. We assume stack and stack_size already have alignment of + // kMaxStackAlignment. + const size_t kMaxStackAlignment = 64; void* const stack_top = - static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0); + static_cast<char*>(stack) + + (stack_grows_down ? stack_size - kMaxStackAlignment : 0); + GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment && + reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0); child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); } -# else +# else const bool use_fork = true; -# endif // GTEST_HAS_CLONE +# endif // GTEST_HAS_CLONE if (use_fork && (child_pid = fork()) == 0) { ExecDeathTestChildMain(&args); _exit(0); } +# endif // GTEST_OS_QNX +# if GTEST_OS_LINUX + GTEST_DEATH_TEST_CHECK_SYSCALL_( + sigaction(SIGPROF, &saved_sigprof_action, NULL)); +# endif // GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_(child_pid != -1); return child_pid; @@ -1009,16 +1133,16 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { // it be closed when the child process does an exec: GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); - const String filter_flag = - String::Format("--%s%s=%s.%s", - GTEST_FLAG_PREFIX_, kFilterFlag, - info->test_case_name(), info->name()); - const String internal_flag = - String::Format("--%s%s=%s|%d|%d|%d", - GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag, - file_, line_, death_test_index, pipe_fd[1]); + const std::string filter_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + + info->test_case_name() + "." + info->name(); + const std::string internal_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + + file_ + "|" + StreamableToString(line_) + "|" + + StreamableToString(death_test_index) + "|" + + StreamableToString(pipe_fd[1]); Arguments args; - args.AddArguments(GetArgvs()); + args.AddArguments(GetArgvsForDeathTestChildProcess()); args.AddArgument(filter_flag.c_str()); args.AddArgument(internal_flag.c_str()); @@ -1029,7 +1153,7 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { // is necessary. FlushInfoLog(); - const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]); + const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_child_pid(child_pid); set_read_fd(pipe_fd[0]); @@ -1055,9 +1179,10 @@ bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, if (flag != NULL) { if (death_test_index > flag->index()) { - DeathTest::set_last_death_test_message(String::Format( - "Death test count (%d) somehow exceeded expected maximum (%d)", - death_test_index, flag->index())); + DeathTest::set_last_death_test_message( + "Death test count (" + StreamableToString(death_test_index) + + ") somehow exceeded expected maximum (" + + StreamableToString(flag->index()) + ")"); return false; } @@ -1086,38 +1211,15 @@ bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, # endif // GTEST_OS_WINDOWS else { // NOLINT - this is more readable than unbalanced brackets inside #if. - DeathTest::set_last_death_test_message(String::Format( - "Unknown death test style \"%s\" encountered", - GTEST_FLAG(death_test_style).c_str())); + DeathTest::set_last_death_test_message( + "Unknown death test style \"" + GTEST_FLAG(death_test_style) + + "\" encountered"); return false; } return true; } -// Pin the vtable to this file. -DeathTestFactory::~DeathTestFactory() {} - -// Splits a given string on a given delimiter, populating a given -// vector with the fields. GTEST_HAS_DEATH_TEST implies that we have -// ::std::string, so we can use it here. -static void SplitString(const ::std::string& str, char delimiter, - ::std::vector< ::std::string>* dest) { - ::std::vector< ::std::string> parsed; - ::std::string::size_type pos = 0; - while (::testing::internal::AlwaysTrue()) { - const ::std::string::size_type colon = str.find(delimiter, pos); - if (colon == ::std::string::npos) { - parsed.push_back(str.substr(pos)); - break; - } else { - parsed.push_back(str.substr(pos, colon - pos)); - pos = colon + 1; - } - } - dest->swap(parsed); -} - # if GTEST_OS_WINDOWS // Recreates the pipe and event handles from the provided parameters, // signals the event, and returns a file descriptor wrapped around the pipe @@ -1129,8 +1231,8 @@ int GetStatusFileDescriptor(unsigned int parent_process_id, FALSE, // Non-inheritable. parent_process_id)); if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { - DeathTestAbort(String::Format("Unable to open parent process %u", - parent_process_id)); + DeathTestAbort("Unable to open parent process " + + StreamableToString(parent_process_id)); } // TODO(vladl@google.com): Replace the following check with a @@ -1150,9 +1252,10 @@ int GetStatusFileDescriptor(unsigned int parent_process_id, // DUPLICATE_SAME_ACCESS is used. FALSE, // Request non-inheritable handler. DUPLICATE_SAME_ACCESS)) { - DeathTestAbort(String::Format( - "Unable to duplicate the pipe handle %Iu from the parent process %u", - write_handle_as_size_t, parent_process_id)); + DeathTestAbort("Unable to duplicate the pipe handle " + + StreamableToString(write_handle_as_size_t) + + " from the parent process " + + StreamableToString(parent_process_id)); } const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t); @@ -1163,17 +1266,18 @@ int GetStatusFileDescriptor(unsigned int parent_process_id, 0x0, FALSE, DUPLICATE_SAME_ACCESS)) { - DeathTestAbort(String::Format( - "Unable to duplicate the event handle %Iu from the parent process %u", - event_handle_as_size_t, parent_process_id)); + DeathTestAbort("Unable to duplicate the event handle " + + StreamableToString(event_handle_as_size_t) + + " from the parent process " + + StreamableToString(parent_process_id)); } const int write_fd = ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND); if (write_fd == -1) { - DeathTestAbort(String::Format( - "Unable to convert pipe handle %Iu to a file descriptor", - write_handle_as_size_t)); + DeathTestAbort("Unable to convert pipe handle " + + StreamableToString(write_handle_as_size_t) + + " to a file descriptor"); } // Signals the parent that the write end of the pipe has been acquired @@ -1210,9 +1314,8 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { || !ParseNaturalNumber(fields[3], &parent_process_id) || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { - DeathTestAbort(String::Format( - "Bad --gtest_internal_run_death_test flag: %s", - GTEST_FLAG(internal_run_death_test).c_str())); + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + + GTEST_FLAG(internal_run_death_test)); } write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t, @@ -1223,9 +1326,8 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[3], &write_fd)) { - DeathTestAbort(String::Format( - "Bad --gtest_internal_run_death_test flag: %s", - GTEST_FLAG(internal_run_death_test).c_str())); + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + + GTEST_FLAG(internal_run_death_test)); } # endif // GTEST_OS_WINDOWS diff --git a/gnu/llvm/utils/unittest/googletest/src/gtest-filepath.cc b/gnu/llvm/utils/unittest/googletest/src/gtest-filepath.cc index ad1bab8e9f5..0292dc11957 100644 --- a/gnu/llvm/utils/unittest/googletest/src/gtest-filepath.cc +++ b/gnu/llvm/utils/unittest/googletest/src/gtest-filepath.cc @@ -29,6 +29,7 @@ // // Authors: keith.ray@gmail.com (Keith Ray) +#include "gtest/gtest-message.h" #include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-port.h" @@ -39,8 +40,8 @@ #elif GTEST_OS_WINDOWS # include <direct.h> # include <io.h> -#elif GTEST_OS_SYMBIAN || GTEST_OS_NACL -// Symbian OpenC and NaCl have PATH_MAX in sys/syslimits.h +#elif GTEST_OS_SYMBIAN +// Symbian OpenC has PATH_MAX in sys/syslimits.h # include <sys/syslimits.h> #else # include <limits.h> @@ -96,7 +97,7 @@ static bool IsPathSeparator(char c) { // Returns the current working directory, or "" if unsuccessful. FilePath FilePath::GetCurrentDir() { -#if GTEST_OS_WINDOWS_MOBILE +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT // Windows CE doesn't have a current directory, so we just return // something reasonable. return FilePath(kCurrentDirectoryString); @@ -105,7 +106,14 @@ FilePath FilePath::GetCurrentDir() { return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); #else char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; - return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); + char* result = getcwd(cwd, sizeof(cwd)); +# if GTEST_OS_NACL + // getcwd will likely fail in NaCl due to the sandbox, so return something + // reasonable. The user may have provided a shim implementation for getcwd, + // however, so fallback only when failure is detected. + return FilePath(result == NULL ? kCurrentDirectoryString : cwd); +# endif // GTEST_OS_NACL + return FilePath(result == NULL ? "" : cwd); #endif // GTEST_OS_WINDOWS_MOBILE } @@ -114,14 +122,15 @@ FilePath FilePath::GetCurrentDir() { // FilePath("dir/file"). If a case-insensitive extension is not // found, returns a copy of the original FilePath. FilePath FilePath::RemoveExtension(const char* extension) const { - String dot_extension(String::Format(".%s", extension)); - if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) { - return FilePath(String(pathname_.c_str(), pathname_.length() - 4)); + const std::string dot_extension = std::string(".") + extension; + if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { + return FilePath(pathname_.substr( + 0, pathname_.length() - dot_extension.length())); } return *this; } -// Returns a pointer to the last occurrence of a valid path separator in +// Returns a pointer to the last occurence of a valid path separator in // the FilePath. On Windows, for example, both '/' and '\' are valid path // separators. Returns NULL if no path separator was found. const char* FilePath::FindLastPathSeparator() const { @@ -145,7 +154,7 @@ const char* FilePath::FindLastPathSeparator() const { // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath FilePath::RemoveDirectoryName() const { const char* const last_sep = FindLastPathSeparator(); - return last_sep ? FilePath(String(last_sep + 1)) : *this; + return last_sep ? FilePath(last_sep + 1) : *this; } // RemoveFileName returns the directory path with the filename removed. @@ -156,9 +165,9 @@ FilePath FilePath::RemoveDirectoryName() const { // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath FilePath::RemoveFileName() const { const char* const last_sep = FindLastPathSeparator(); - String dir; + std::string dir; if (last_sep) { - dir = String(c_str(), last_sep + 1 - c_str()); + dir = std::string(c_str(), last_sep + 1 - c_str()); } else { dir = kCurrentDirectoryString; } @@ -175,11 +184,12 @@ FilePath FilePath::MakeFileName(const FilePath& directory, const FilePath& base_name, int number, const char* extension) { - String file; + std::string file; if (number == 0) { - file = String::Format("%s.%s", base_name.c_str(), extension); + file = base_name.string() + "." + extension; } else { - file = String::Format("%s_%d.%s", base_name.c_str(), number, extension); + file = base_name.string() + "_" + StreamableToString(number) + + "." + extension; } return ConcatPaths(directory, FilePath(file)); } @@ -191,8 +201,7 @@ FilePath FilePath::ConcatPaths(const FilePath& directory, if (directory.IsEmpty()) return relative_path; const FilePath dir(directory.RemoveTrailingPathSeparator()); - return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator, - relative_path.c_str())); + return FilePath(dir.string() + kPathSeparator + relative_path.string()); } // Returns true if pathname describes something findable in the file-system, @@ -336,7 +345,7 @@ bool FilePath::CreateFolder() const { // On Windows platform, uses \ as the separator, other platforms use /. FilePath FilePath::RemoveTrailingPathSeparator() const { return IsDirectory() - ? FilePath(String(pathname_.c_str(), pathname_.length() - 1)) + ? FilePath(pathname_.substr(0, pathname_.length() - 1)) : *this; } diff --git a/gnu/llvm/utils/unittest/googletest/src/gtest-internal-inl.h b/gnu/llvm/utils/unittest/googletest/src/gtest-internal-inl.h index f610cfd17b8..ed8a682a964 100644 --- a/gnu/llvm/utils/unittest/googletest/src/gtest-internal-inl.h +++ b/gnu/llvm/utils/unittest/googletest/src/gtest-internal-inl.h @@ -40,7 +40,7 @@ // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is // part of Google Test's implementation; otherwise it's undefined. #if !GTEST_IMPLEMENTATION_ -// A user is trying to include this from his code - just say no. +// If this file is included from the user's code, just say no. # error "gtest-internal-inl.h is part of Google Test's internal implementation." # error "It must not be included except by Google Test itself." #endif // GTEST_IMPLEMENTATION_ @@ -58,6 +58,11 @@ #include "gtest/internal/gtest-port.h" +#if GTEST_CAN_STREAM_RESULTS_ +# include <arpa/inet.h> // NOLINT +# include <netdb.h> // NOLINT +#endif + #if GTEST_OS_WINDOWS # include <windows.h> // NOLINT #endif // GTEST_OS_WINDOWS @@ -95,6 +100,7 @@ const char kShuffleFlag[] = "shuffle"; const char kStackTraceDepthFlag[] = "stack_trace_depth"; const char kStreamResultToFlag[] = "stream_result_to"; const char kThrowOnFailureFlag[] = "throw_on_failure"; +const char kFlagfileFlag[] = "flagfile"; // A valid random seed must be in [1, kMaxRandomSeed]. const int kMaxRandomSeed = 99999; @@ -112,6 +118,12 @@ GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); // Formats the given time in milliseconds as seconds. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); +// Converts the given time in milliseconds to a date string in the ISO 8601 +// format, without the timezone information. N.B.: due to the use the +// non-reentrant localtime() function, this function is not thread safe. Do +// not use it in any code that can be called from multiple threads. +GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); + // Parses a string for an Int32 flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns @@ -151,79 +163,74 @@ class GTestFlagSaver { public: // The c'tor. GTestFlagSaver() { + also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); + break_on_failure_ = GTEST_FLAG(break_on_failure); + catch_exceptions_ = GTEST_FLAG(catch_exceptions); color_ = GTEST_FLAG(color); death_test_style_ = GTEST_FLAG(death_test_style); + death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); filter_ = GTEST_FLAG(filter); internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); + list_tests_ = GTEST_FLAG(list_tests); output_ = GTEST_FLAG(output); - stream_result_to_ = GTEST_FLAG(stream_result_to); - + print_time_ = GTEST_FLAG(print_time); random_seed_ = GTEST_FLAG(random_seed); repeat_ = GTEST_FLAG(repeat); - stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); - - also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); - break_on_failure_ = GTEST_FLAG(break_on_failure); - catch_exceptions_ = GTEST_FLAG(catch_exceptions); - death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); - list_tests_ = GTEST_FLAG(list_tests); - print_time_ = GTEST_FLAG(print_time); shuffle_ = GTEST_FLAG(shuffle); + stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); + stream_result_to_ = GTEST_FLAG(stream_result_to); throw_on_failure_ = GTEST_FLAG(throw_on_failure); } // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. ~GTestFlagSaver() { + GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; + GTEST_FLAG(break_on_failure) = break_on_failure_; + GTEST_FLAG(catch_exceptions) = catch_exceptions_; GTEST_FLAG(color) = color_; GTEST_FLAG(death_test_style) = death_test_style_; + GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; GTEST_FLAG(filter) = filter_; GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; + GTEST_FLAG(list_tests) = list_tests_; GTEST_FLAG(output) = output_; - GTEST_FLAG(stream_result_to) = stream_result_to_; - + GTEST_FLAG(print_time) = print_time_; GTEST_FLAG(random_seed) = random_seed_; GTEST_FLAG(repeat) = repeat_; - GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; - - GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; - GTEST_FLAG(break_on_failure) = break_on_failure_; - GTEST_FLAG(catch_exceptions) = catch_exceptions_; - GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; - GTEST_FLAG(list_tests) = list_tests_; - GTEST_FLAG(print_time) = print_time_; GTEST_FLAG(shuffle) = shuffle_; + GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; + GTEST_FLAG(stream_result_to) = stream_result_to_; GTEST_FLAG(throw_on_failure) = throw_on_failure_; } + private: // Fields for saving the original values of flags. - String color_; - String death_test_style_; - String filter_; - String internal_run_death_test_; - String output_; - String stream_result_to_; - internal::Int32 random_seed_; - internal::Int32 repeat_; - internal::Int32 stack_trace_depth_; bool also_run_disabled_tests_; bool break_on_failure_; bool catch_exceptions_; + std::string color_; + std::string death_test_style_; bool death_test_use_fork_; + std::string filter_; + std::string internal_run_death_test_; bool list_tests_; + std::string output_; bool print_time_; + internal::Int32 random_seed_; + internal::Int32 repeat_; bool shuffle_; + internal::Int32 stack_trace_depth_; + std::string stream_result_to_; bool throw_on_failure_; } GTEST_ATTRIBUTE_UNUSED_; // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. -// The output buffer str must containt at least 32 characters. -// The function returns the address of the output buffer. // If the code_point is not a valid Unicode code point -// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output -// as '(Invalid Unicode 0xXXXXXXXX)'. -GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str); +// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted +// to "(Invalid Unicode 0xXXXXXXXX)". +GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: @@ -238,7 +245,7 @@ GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str); // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. -GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars); +GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this @@ -342,16 +349,15 @@ class TestPropertyKeyIs { // Constructor. // // TestPropertyKeyIs has NO default constructor. - explicit TestPropertyKeyIs(const char* key) - : key_(key) {} + explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} // Returns true iff the test name of test property matches on key_. bool operator()(const TestProperty& test_property) const { - return String(test_property.key()).Compare(key_) == 0; + return test_property.key() == key_; } private: - String key_; + std::string key_; }; // Class UnitTestOptions. @@ -369,12 +375,12 @@ class GTEST_API_ UnitTestOptions { // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. - static String GetOutputFormat(); + static std::string GetOutputFormat(); // Returns the absolute path of the requested output file, or the // default (test_detail.xml in the original working directory) if // none was explicitly specified. - static String GetAbsolutePathToOutputFile(); + static std::string GetAbsolutePathToOutputFile(); // Functions for processing the gtest_filter flag. @@ -387,8 +393,8 @@ class GTEST_API_ UnitTestOptions { // Returns true iff the user-specified filter matches the test case // name and the test name. - static bool FilterMatchesTest(const String &test_case_name, - const String &test_name); + static bool FilterMatchesTest(const std::string &test_case_name, + const std::string &test_name); #if GTEST_OS_WINDOWS // Function for supporting the gtest_catch_exception flag. @@ -401,7 +407,7 @@ class GTEST_API_ UnitTestOptions { // Returns true if "name" matches the ':' separated list of glob-style // filters in "filter". - static bool MatchesFilter(const String& name, const char* filter); + static bool MatchesFilter(const std::string& name, const char* filter); }; // Returns the current application's name, removing directory path if that @@ -412,21 +418,25 @@ GTEST_API_ FilePath GetCurrentExecutableName(); class OsStackTraceGetterInterface { public: OsStackTraceGetterInterface() {} - virtual ~OsStackTraceGetterInterface(); + virtual ~OsStackTraceGetterInterface() {} - // Returns the current OS stack trace as a String. Parameters: + // Returns the current OS stack trace as an std::string. Parameters: // // max_depth - the maximum number of stack frames to be included // in the trace. // skip_count - the number of top frames to be skipped; doesn't count // against max_depth. - virtual String CurrentStackTrace(int max_depth, int skip_count) = 0; + virtual string CurrentStackTrace(int max_depth, int skip_count) = 0; // UponLeavingGTest() should be called immediately before Google Test calls // user code. It saves some information about the current stack that // CurrentStackTrace() will use to find and hide Google Test stack frames. virtual void UponLeavingGTest() = 0; + // This string is inserted in place of stack frames that are part of + // Google Test's implementation. + static const char* const kElidedFramesMarker; + private: GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); }; @@ -434,23 +444,12 @@ class OsStackTraceGetterInterface { // A working implementation of the OsStackTraceGetterInterface interface. class OsStackTraceGetter : public OsStackTraceGetterInterface { public: - OsStackTraceGetter() : caller_frame_(NULL) {} - String CurrentStackTrace(int max_depth, int skip_count) override; - void UponLeavingGTest() override; + OsStackTraceGetter() {} - // This string is inserted in place of stack frames that are part of - // Google Test's implementation. - static const char* const kElidedFramesMarker; + virtual string CurrentStackTrace(int max_depth, int skip_count); + virtual void UponLeavingGTest(); private: - Mutex mutex_; // protects all internal state - - // We save the stack frame below the frame that calls user code. - // We do this because the address of the frame immediately below - // the user code changes between the call to UponLeavingGTest() - // and any calls to CurrentStackTrace() from within the user code. - void* caller_frame_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); }; @@ -458,7 +457,7 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface { struct TraceInfo { const char* file; int line; - String message; + std::string message; }; // This is the default global test part result reporter used in UnitTestImpl. @@ -469,7 +468,7 @@ class DefaultGlobalTestPartResultReporter explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. Reports the test part // result in the current test. - void ReportTestPartResult(const TestPartResult &result) override; + virtual void ReportTestPartResult(const TestPartResult& result); private: UnitTestImpl* const unit_test_; @@ -485,7 +484,7 @@ class DefaultPerThreadTestPartResultReporter explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. The implementation just // delegates to the current global test part result reporter of *unit_test_. - void ReportTestPartResult(const TestPartResult &result) override; + virtual void ReportTestPartResult(const TestPartResult& result); private: UnitTestImpl* const unit_test_; @@ -542,15 +541,25 @@ class GTEST_API_ UnitTestImpl { // Gets the number of failed tests. int failed_test_count() const; + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + // Gets the number of disabled tests. int disabled_test_count() const; + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + // Gets the number of all tests. int total_test_count() const; // Gets the number of tests that should run. int test_to_run_count() const; + // Gets the time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp() const { return start_timestamp_; } + // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } @@ -599,7 +608,7 @@ class GTEST_API_ UnitTestImpl { // getter, and returns it. OsStackTraceGetterInterface* os_stack_trace_getter(); - // Returns the current OS stack trace as a String. + // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter @@ -609,7 +618,7 @@ class GTEST_API_ UnitTestImpl { // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. - String CurrentOsStackTraceExceptTop(int skip_count); + std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; // Finds and returns a TestCase with the given name. If one doesn't // exist, creates one and returns it. @@ -699,6 +708,12 @@ class GTEST_API_ UnitTestImpl { ad_hoc_test_result_.Clear(); } + // Adds a TestProperty to the current TestResult object when invoked in a + // context of a test or a test case, or to the global property set. If the + // result already contains a property with the same key, the value will be + // updated. + void RecordProperty(const TestProperty& test_property); + enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL @@ -883,6 +898,10 @@ class GTEST_API_ UnitTestImpl { // Our random number generator. internal::Random random_; + // The time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp_; + // How long the test took to run, in milliseconds. TimeInMillis elapsed_time_; @@ -938,33 +957,7 @@ GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); // Returns the message describing the last system error, regardless of the // platform. -GTEST_API_ String GetLastErrnoDescription(); - -# if GTEST_OS_WINDOWS -// Provides leak-safe Windows kernel handle ownership. -class AutoHandle { - public: - AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} - explicit AutoHandle(HANDLE handle) : handle_(handle) {} - - ~AutoHandle() { Reset(); } - - HANDLE Get() const { return handle_; } - void Reset() { Reset(INVALID_HANDLE_VALUE); } - void Reset(HANDLE handle) { - if (handle != handle_) { - if (handle_ != INVALID_HANDLE_VALUE) - ::CloseHandle(handle_); - handle_ = handle; - } - } - - private: - HANDLE handle_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); -}; -# endif // GTEST_OS_WINDOWS +GTEST_API_ std::string GetLastErrnoDescription(); // Attempts to parse a string into a positive integer pointed to by the // number parameter. Returns true if that is possible. @@ -1021,8 +1014,9 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) { class TestResultAccessor { public: static void RecordProperty(TestResult* test_result, + const std::string& xml_element, const TestProperty& property) { - test_result->RecordProperty(property); + test_result->RecordProperty(xml_element, property); } static void ClearTestPartResults(TestResult* test_result) { @@ -1035,6 +1029,154 @@ class TestResultAccessor { } }; +#if GTEST_CAN_STREAM_RESULTS_ + +// Streams test results to the given port on the given host machine. +class GTEST_API_ StreamingListener : public EmptyTestEventListener { + public: + // Abstract base class for writing strings to a socket. + class AbstractSocketWriter { + public: + virtual ~AbstractSocketWriter() {} + + // Sends a string to the socket. + virtual void Send(const string& message) = 0; + + // Closes the socket. + virtual void CloseConnection() {} + + // Sends a string and a newline to the socket. + void SendLn(const string& message) { + Send(message + "\n"); + } + }; + + // Concrete class for actually writing strings to a socket. + class SocketWriter : public AbstractSocketWriter { + public: + SocketWriter(const string& host, const string& port) + : sockfd_(-1), host_name_(host), port_num_(port) { + MakeConnection(); + } + + virtual ~SocketWriter() { + if (sockfd_ != -1) + CloseConnection(); + } + + // Sends a string to the socket. + virtual void Send(const string& message) { + GTEST_CHECK_(sockfd_ != -1) + << "Send() can be called only when there is a connection."; + + const int len = static_cast<int>(message.length()); + if (write(sockfd_, message.c_str(), len) != len) { + GTEST_LOG_(WARNING) + << "stream_result_to: failed to stream to " + << host_name_ << ":" << port_num_; + } + } + + private: + // Creates a client socket and connects to the server. + void MakeConnection(); + + // Closes the socket. + void CloseConnection() { + GTEST_CHECK_(sockfd_ != -1) + << "CloseConnection() can be called only when there is a connection."; + + close(sockfd_); + sockfd_ = -1; + } + + int sockfd_; // socket file descriptor + const string host_name_; + const string port_num_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); + }; // class SocketWriter + + // Escapes '=', '&', '%', and '\n' characters in str as "%xx". + static string UrlEncode(const char* str); + + StreamingListener(const string& host, const string& port) + : socket_writer_(new SocketWriter(host, port)) { Start(); } + + explicit StreamingListener(AbstractSocketWriter* socket_writer) + : socket_writer_(socket_writer) { Start(); } + + void OnTestProgramStart(const UnitTest& /* unit_test */) { + SendLn("event=TestProgramStart"); + } + + void OnTestProgramEnd(const UnitTest& unit_test) { + // Note that Google Test current only report elapsed time for each + // test iteration, not for the entire test program. + SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); + + // Notify the streaming server to stop. + socket_writer_->CloseConnection(); + } + + void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { + SendLn("event=TestIterationStart&iteration=" + + StreamableToString(iteration)); + } + + void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { + SendLn("event=TestIterationEnd&passed=" + + FormatBool(unit_test.Passed()) + "&elapsed_time=" + + StreamableToString(unit_test.elapsed_time()) + "ms"); + } + + void OnTestCaseStart(const TestCase& test_case) { + SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); + } + + void OnTestCaseEnd(const TestCase& test_case) { + SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + + "ms"); + } + + void OnTestStart(const TestInfo& test_info) { + SendLn(std::string("event=TestStart&name=") + test_info.name()); + } + + void OnTestEnd(const TestInfo& test_info) { + SendLn("event=TestEnd&passed=" + + FormatBool((test_info.result())->Passed()) + + "&elapsed_time=" + + StreamableToString((test_info.result())->elapsed_time()) + "ms"); + } + + void OnTestPartResult(const TestPartResult& test_part_result) { + const char* file_name = test_part_result.file_name(); + if (file_name == NULL) + file_name = ""; + SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + + "&line=" + StreamableToString(test_part_result.line_number()) + + "&message=" + UrlEncode(test_part_result.message())); + } + + private: + // Sends the given message and a newline to the socket. + void SendLn(const string& message) { socket_writer_->SendLn(message); } + + // Called at the start of streaming to notify the receiver what + // protocol we are using. + void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } + + string FormatBool(bool value) { return value ? "1" : "0"; } + + const scoped_ptr<AbstractSocketWriter> socket_writer_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); +}; // class StreamingListener + +#endif // GTEST_CAN_STREAM_RESULTS_ + } // namespace internal } // namespace testing diff --git a/gnu/llvm/utils/unittest/googletest/src/gtest-port.cc b/gnu/llvm/utils/unittest/googletest/src/gtest-port.cc index 94fc57f89b3..e5bf3dd2be4 100644 --- a/gnu/llvm/utils/unittest/googletest/src/gtest-port.cc +++ b/gnu/llvm/utils/unittest/googletest/src/gtest-port.cc @@ -35,15 +35,16 @@ #include <stdlib.h> #include <stdio.h> #include <string.h> +#include <fstream> -#if GTEST_OS_WINDOWS_MOBILE -# include <windows.h> // For TerminateProcess() -#elif GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS +# include <windows.h> # include <io.h> # include <sys/stat.h> +# include <map> // Used in ThreadLocal. #else # include <unistd.h> -#endif // GTEST_OS_WINDOWS_MOBILE +#endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC # include <mach/mach_init.h> @@ -51,6 +52,17 @@ # include <mach/vm_map.h> #endif // GTEST_OS_MAC +#if GTEST_OS_QNX +# include <devctl.h> +# include <fcntl.h> +# include <sys/procfs.h> +#endif // GTEST_OS_QNX + +#if GTEST_OS_AIX +# include <procinfo.h> +# include <sys/types.h> +#endif // GTEST_OS_AIX + #include "gtest/gtest-spi.h" #include "gtest/gtest-message.h" #include "gtest/internal/gtest-internal.h" @@ -58,9 +70,9 @@ // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. +// included, or there will be a compiler error. This trick exists to +// prevent the accidental inclusion of gtest-internal-inl.h in the +// user's code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ @@ -77,10 +89,31 @@ const int kStdOutFileno = STDOUT_FILENO; const int kStdErrFileno = STDERR_FILENO; #endif // _MSC_VER -#if GTEST_OS_MAC +#if GTEST_OS_LINUX + +namespace { +template <typename T> +T ReadProcFileField(const string& filename, int field) { + std::string dummy; + std::ifstream file(filename.c_str()); + while (field-- > 0) { + file >> dummy; + } + T output = 0; + file >> output; + return output; +} +} // namespace + +// Returns the number of active threads, or 0 when there is an error. +size_t GetThreadCount() { + const string filename = + (Message() << "/proc/" << getpid() << "/stat").GetString(); + return ReadProcFileField<int>(filename, 19); +} + +#elif GTEST_OS_MAC -// Returns the number of threads running in the process, or 0 to indicate that -// we cannot detect it. size_t GetThreadCount() { const task_t task = mach_task_self(); mach_msg_type_number_t thread_count; @@ -98,6 +131,39 @@ size_t GetThreadCount() { } } +#elif GTEST_OS_QNX + +// Returns the number of threads running in the process, or 0 to indicate that +// we cannot detect it. +size_t GetThreadCount() { + const int fd = open("/proc/self/as", O_RDONLY); + if (fd < 0) { + return 0; + } + procfs_info process_info; + const int status = + devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL); + close(fd); + if (status == EOK) { + return static_cast<size_t>(process_info.num_threads); + } else { + return 0; + } +} + +#elif GTEST_OS_AIX + +size_t GetThreadCount() { + struct procentry64 entry; + pid_t pid = getpid(); + int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1); + if (status == 1) { + return entry.pi_thcount; + } else { + return 0; + } +} + #else size_t GetThreadCount() { @@ -106,7 +172,390 @@ size_t GetThreadCount() { return 0; } -#endif // GTEST_OS_MAC +#endif // GTEST_OS_LINUX + +#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS + +void SleepMilliseconds(int n) { + ::Sleep(n); +} + +AutoHandle::AutoHandle() + : handle_(INVALID_HANDLE_VALUE) {} + +AutoHandle::AutoHandle(Handle handle) + : handle_(handle) {} + +AutoHandle::~AutoHandle() { + Reset(); +} + +AutoHandle::Handle AutoHandle::Get() const { + return handle_; +} + +void AutoHandle::Reset() { + Reset(INVALID_HANDLE_VALUE); +} + +void AutoHandle::Reset(HANDLE handle) { + // Resetting with the same handle we already own is invalid. + if (handle_ != handle) { + if (IsCloseable()) { + ::CloseHandle(handle_); + } + handle_ = handle; + } else { + GTEST_CHECK_(!IsCloseable()) + << "Resetting a valid handle to itself is likely a programmer error " + "and thus not allowed."; + } +} + +bool AutoHandle::IsCloseable() const { + // Different Windows APIs may use either of these values to represent an + // invalid handle. + return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE; +} + +Notification::Notification() + : event_(::CreateEvent(NULL, // Default security attributes. + TRUE, // Do not reset automatically. + FALSE, // Initially unset. + NULL)) { // Anonymous event. + GTEST_CHECK_(event_.Get() != NULL); +} + +void Notification::Notify() { + GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); +} + +void Notification::WaitForNotification() { + GTEST_CHECK_( + ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0); +} + +Mutex::Mutex() + : owner_thread_id_(0), + type_(kDynamic), + critical_section_init_phase_(0), + critical_section_(new CRITICAL_SECTION) { + ::InitializeCriticalSection(critical_section_); +} + +Mutex::~Mutex() { + // Static mutexes are leaked intentionally. It is not thread-safe to try + // to clean them up. + // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires + // nothing to clean it up but is available only on Vista and later. + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx + if (type_ == kDynamic) { + ::DeleteCriticalSection(critical_section_); + delete critical_section_; + critical_section_ = NULL; + } +} + +void Mutex::Lock() { + ThreadSafeLazyInit(); + ::EnterCriticalSection(critical_section_); + owner_thread_id_ = ::GetCurrentThreadId(); +} + +void Mutex::Unlock() { + ThreadSafeLazyInit(); + // We don't protect writing to owner_thread_id_ here, as it's the + // caller's responsibility to ensure that the current thread holds the + // mutex when this is called. + owner_thread_id_ = 0; + ::LeaveCriticalSection(critical_section_); +} + +// Does nothing if the current thread holds the mutex. Otherwise, crashes +// with high probability. +void Mutex::AssertHeld() { + ThreadSafeLazyInit(); + GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId()) + << "The current thread is not holding the mutex @" << this; +} + +// Initializes owner_thread_id_ and critical_section_ in static mutexes. +void Mutex::ThreadSafeLazyInit() { + // Dynamic mutexes are initialized in the constructor. + if (type_ == kStatic) { + switch ( + ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) { + case 0: + // If critical_section_init_phase_ was 0 before the exchange, we + // are the first to test it and need to perform the initialization. + owner_thread_id_ = 0; + critical_section_ = new CRITICAL_SECTION; + ::InitializeCriticalSection(critical_section_); + // Updates the critical_section_init_phase_ to 2 to signal + // initialization complete. + GTEST_CHECK_(::InterlockedCompareExchange( + &critical_section_init_phase_, 2L, 1L) == + 1L); + break; + case 1: + // Somebody else is already initializing the mutex; spin until they + // are done. + while (::InterlockedCompareExchange(&critical_section_init_phase_, + 2L, + 2L) != 2L) { + // Possibly yields the rest of the thread's time slice to other + // threads. + ::Sleep(0); + } + break; + + case 2: + break; // The mutex is already initialized and ready for use. + + default: + GTEST_CHECK_(false) + << "Unexpected value of critical_section_init_phase_ " + << "while initializing a static mutex."; + } + } +} + +namespace { + +class ThreadWithParamSupport : public ThreadWithParamBase { + public: + static HANDLE CreateThread(Runnable* runnable, + Notification* thread_can_start) { + ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); + DWORD thread_id; + // TODO(yukawa): Consider to use _beginthreadex instead. + HANDLE thread_handle = ::CreateThread( + NULL, // Default security. + 0, // Default stack size. + &ThreadWithParamSupport::ThreadMain, + param, // Parameter to ThreadMainStatic + 0x0, // Default creation flags. + &thread_id); // Need a valid pointer for the call to work under Win98. + GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error " + << ::GetLastError() << "."; + if (thread_handle == NULL) { + delete param; + } + return thread_handle; + } + + private: + struct ThreadMainParam { + ThreadMainParam(Runnable* runnable, Notification* thread_can_start) + : runnable_(runnable), + thread_can_start_(thread_can_start) { + } + scoped_ptr<Runnable> runnable_; + // Does not own. + Notification* thread_can_start_; + }; + + static DWORD WINAPI ThreadMain(void* ptr) { + // Transfers ownership. + scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr)); + if (param->thread_can_start_ != NULL) + param->thread_can_start_->WaitForNotification(); + param->runnable_->Run(); + return 0; + } + + // Prohibit instantiation. + ThreadWithParamSupport(); + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport); +}; + +} // namespace + +ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, + Notification* thread_can_start) + : thread_(ThreadWithParamSupport::CreateThread(runnable, + thread_can_start)) { +} + +ThreadWithParamBase::~ThreadWithParamBase() { + Join(); +} + +void ThreadWithParamBase::Join() { + GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) + << "Failed to join the thread with error " << ::GetLastError() << "."; +} + +// Maps a thread to a set of ThreadIdToThreadLocals that have values +// instantiated on that thread and notifies them when the thread exits. A +// ThreadLocal instance is expected to persist until all threads it has +// values on have terminated. +class ThreadLocalRegistryImpl { + public: + // Registers thread_local_instance as having value on the current thread. + // Returns a value that can be used to identify the thread from other threads. + static ThreadLocalValueHolderBase* GetValueOnCurrentThread( + const ThreadLocalBase* thread_local_instance) { + DWORD current_thread = ::GetCurrentThreadId(); + MutexLock lock(&mutex_); + ThreadIdToThreadLocals* const thread_to_thread_locals = + GetThreadLocalsMapLocked(); + ThreadIdToThreadLocals::iterator thread_local_pos = + thread_to_thread_locals->find(current_thread); + if (thread_local_pos == thread_to_thread_locals->end()) { + thread_local_pos = thread_to_thread_locals->insert( + std::make_pair(current_thread, ThreadLocalValues())).first; + StartWatcherThreadFor(current_thread); + } + ThreadLocalValues& thread_local_values = thread_local_pos->second; + ThreadLocalValues::iterator value_pos = + thread_local_values.find(thread_local_instance); + if (value_pos == thread_local_values.end()) { + value_pos = + thread_local_values + .insert(std::make_pair( + thread_local_instance, + linked_ptr<ThreadLocalValueHolderBase>( + thread_local_instance->NewValueForCurrentThread()))) + .first; + } + return value_pos->second.get(); + } + + static void OnThreadLocalDestroyed( + const ThreadLocalBase* thread_local_instance) { + std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders; + // Clean up the ThreadLocalValues data structure while holding the lock, but + // defer the destruction of the ThreadLocalValueHolderBases. + { + MutexLock lock(&mutex_); + ThreadIdToThreadLocals* const thread_to_thread_locals = + GetThreadLocalsMapLocked(); + for (ThreadIdToThreadLocals::iterator it = + thread_to_thread_locals->begin(); + it != thread_to_thread_locals->end(); + ++it) { + ThreadLocalValues& thread_local_values = it->second; + ThreadLocalValues::iterator value_pos = + thread_local_values.find(thread_local_instance); + if (value_pos != thread_local_values.end()) { + value_holders.push_back(value_pos->second); + thread_local_values.erase(value_pos); + // This 'if' can only be successful at most once, so theoretically we + // could break out of the loop here, but we don't bother doing so. + } + } + } + // Outside the lock, let the destructor for 'value_holders' deallocate the + // ThreadLocalValueHolderBases. + } + + static void OnThreadExit(DWORD thread_id) { + GTEST_CHECK_(thread_id != 0) << ::GetLastError(); + std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders; + // Clean up the ThreadIdToThreadLocals data structure while holding the + // lock, but defer the destruction of the ThreadLocalValueHolderBases. + { + MutexLock lock(&mutex_); + ThreadIdToThreadLocals* const thread_to_thread_locals = + GetThreadLocalsMapLocked(); + ThreadIdToThreadLocals::iterator thread_local_pos = + thread_to_thread_locals->find(thread_id); + if (thread_local_pos != thread_to_thread_locals->end()) { + ThreadLocalValues& thread_local_values = thread_local_pos->second; + for (ThreadLocalValues::iterator value_pos = + thread_local_values.begin(); + value_pos != thread_local_values.end(); + ++value_pos) { + value_holders.push_back(value_pos->second); + } + thread_to_thread_locals->erase(thread_local_pos); + } + } + // Outside the lock, let the destructor for 'value_holders' deallocate the + // ThreadLocalValueHolderBases. + } + + private: + // In a particular thread, maps a ThreadLocal object to its value. + typedef std::map<const ThreadLocalBase*, + linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues; + // Stores all ThreadIdToThreadLocals having values in a thread, indexed by + // thread's ID. + typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals; + + // Holds the thread id and thread handle that we pass from + // StartWatcherThreadFor to WatcherThreadFunc. + typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle; + + static void StartWatcherThreadFor(DWORD thread_id) { + // The returned handle will be kept in thread_map and closed by + // watcher_thread in WatcherThreadFunc. + HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, + FALSE, + thread_id); + GTEST_CHECK_(thread != NULL); + // We need to to pass a valid thread ID pointer into CreateThread for it + // to work correctly under Win98. + DWORD watcher_thread_id; + HANDLE watcher_thread = ::CreateThread( + NULL, // Default security. + 0, // Default stack size + &ThreadLocalRegistryImpl::WatcherThreadFunc, + reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)), + CREATE_SUSPENDED, + &watcher_thread_id); + GTEST_CHECK_(watcher_thread != NULL); + // Give the watcher thread the same priority as ours to avoid being + // blocked by it. + ::SetThreadPriority(watcher_thread, + ::GetThreadPriority(::GetCurrentThread())); + ::ResumeThread(watcher_thread); + ::CloseHandle(watcher_thread); + } + + // Monitors exit from a given thread and notifies those + // ThreadIdToThreadLocals about thread termination. + static DWORD WINAPI WatcherThreadFunc(LPVOID param) { + const ThreadIdAndHandle* tah = + reinterpret_cast<const ThreadIdAndHandle*>(param); + GTEST_CHECK_( + ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); + OnThreadExit(tah->first); + ::CloseHandle(tah->second); + delete tah; + return 0; + } + + // Returns map of thread local instances. + static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() { + mutex_.AssertHeld(); + static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals; + return map; + } + + // Protects access to GetThreadLocalsMapLocked() and its return value. + static Mutex mutex_; + // Protects access to GetThreadMapLocked() and its return value. + static Mutex thread_map_mutex_; +}; + +Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); +Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); + +ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( + const ThreadLocalBase* thread_local_instance) { + return ThreadLocalRegistryImpl::GetValueOnCurrentThread( + thread_local_instance); +} + +void ThreadLocalRegistry::OnThreadLocalDestroyed( + const ThreadLocalBase* thread_local_instance) { + ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); +} + +#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS #if GTEST_USES_POSIX_RE @@ -222,7 +671,7 @@ bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { } // Helper function used by ValidateRegex() to format error messages. -String FormatRegexSyntaxError(const char* regex, int index) { +std::string FormatRegexSyntaxError(const char* regex, int index) { return (Message() << "Syntax error at index " << index << " in simple regular expression \"" << regex << "\": ").GetString(); } @@ -429,15 +878,15 @@ const char kUnknownFile[] = "unknown file"; // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { - const char* const file_name = file == NULL ? kUnknownFile : file; + const std::string file_name(file == NULL ? kUnknownFile : file); if (line < 0) { - return String::Format("%s:", file_name).c_str(); + return file_name + ":"; } #ifdef _MSC_VER - return String::Format("%s(%d):", file_name, line).c_str(); + return file_name + "(" + StreamableToString(line) + "):"; #else - return String::Format("%s:%d:", file_name, line).c_str(); + return file_name + ":" + StreamableToString(line) + ":"; #endif // _MSC_VER } @@ -448,15 +897,14 @@ GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { // to the file location it produces, unlike FormatFileLocation(). GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( const char* file, int line) { - const char* const file_name = file == NULL ? kUnknownFile : file; + const std::string file_name(file == NULL ? kUnknownFile : file); if (line < 0) return file_name; else - return String::Format("%s:%d", file_name, line).c_str(); + return file_name + ":" + StreamableToString(line); } - GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) : severity_(severity) { const char* const marker = @@ -477,10 +925,7 @@ GTestLog::~GTestLog() { } // Disable Microsoft deprecation warnings for POSIX functions called from // this class (creat, dup, dup2, and close) -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 4996) -#endif // _MSC_VER +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) #if GTEST_HAS_STREAM_REDIRECTION @@ -488,8 +933,7 @@ GTestLog::~GTestLog() { class CapturedStream { public: // The ctor redirects the stream to a temporary file. - CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { - + explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { # if GTEST_OS_WINDOWS char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT @@ -505,15 +949,30 @@ class CapturedStream { GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " << temp_file_path; filename_ = temp_file_path; -#elif GTEST_OS_LINUX_ANDROID - char name_template[] = "/sdcard/captured_stderr.XXXXXX"; - const int captured_fd = mkstemp(name_template); - filename_ = name_template; # else - // There's no guarantee that a test has write access to the - // current directory, so we create the temporary file in the /tmp - // directory instead. + // There's no guarantee that a test has write access to the current + // directory, so we create the temporary file in the /tmp directory + // instead. We use /tmp on most systems, and /sdcard on Android. + // That's because Android doesn't have /tmp. +# if GTEST_OS_LINUX_ANDROID + // Note: Android applications are expected to call the framework's + // Context.getExternalStorageDirectory() method through JNI to get + // the location of the world-writable SD Card directory. However, + // this requires a Context handle, which cannot be retrieved + // globally from native code. Doing so also precludes running the + // code as part of a regular standalone executable, which doesn't + // run in a Dalvik process (e.g. when running it through 'adb shell'). + // + // The location /sdcard is directly accessible from native code + // and is the only location (unofficially) supported by the Android + // team. It's generally a symlink to the real SD Card mount point + // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or + // other OEM-customized locations. Never rely on these, and always + // use /sdcard. + char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; +# else char name_template[] = "/tmp/captured_stream.XXXXXX"; +# endif // GTEST_OS_LINUX_ANDROID const int captured_fd = mkstemp(name_template); filename_ = name_template; # endif // GTEST_OS_WINDOWS @@ -526,7 +985,7 @@ class CapturedStream { remove(filename_.c_str()); } - String GetCapturedString() { + std::string GetCapturedString() { if (uncaptured_fd_ != -1) { // Restores the original stream. fflush(NULL); @@ -536,18 +995,12 @@ class CapturedStream { } FILE* const file = posix::FOpen(filename_.c_str(), "r"); - const String content = ReadEntireFile(file); + const std::string content = ReadEntireFile(file); posix::FClose(file); return content; } private: - // Reads the entire content of a file as a String. - static String ReadEntireFile(FILE* file); - - // Returns the size (in bytes) of a file. - static size_t GetFileSize(FILE* file); - const int fd_; // A stream to capture. int uncaptured_fd_; // Name of the temporary file holding the stderr output. @@ -556,38 +1009,7 @@ class CapturedStream { GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); }; -// Returns the size (in bytes) of a file. -size_t CapturedStream::GetFileSize(FILE* file) { - fseek(file, 0, SEEK_END); - return static_cast<size_t>(ftell(file)); -} - -// Reads the entire content of a file as a string. -String CapturedStream::ReadEntireFile(FILE* file) { - const size_t file_size = GetFileSize(file); - char* const buffer = new char[file_size]; - - size_t bytes_last_read = 0; // # of bytes read in the last fread() - size_t bytes_read = 0; // # of bytes read so far - - fseek(file, 0, SEEK_SET); - - // Keeps reading the file until we cannot read further or the - // pre-determined file size is reached. - do { - bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); - bytes_read += bytes_last_read; - } while (bytes_last_read > 0 && bytes_read < file_size); - - const String content(buffer, bytes_read); - delete[] buffer; - - return content; -} - -# ifdef _MSC_VER -# pragma warning(pop) -# endif // _MSC_VER +GTEST_DISABLE_MSC_WARNINGS_POP_() static CapturedStream* g_captured_stderr = NULL; static CapturedStream* g_captured_stdout = NULL; @@ -602,8 +1024,8 @@ void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { } // Stops capturing the output stream and returns the captured string. -String GetCapturedStream(CapturedStream** captured_stream) { - const String content = (*captured_stream)->GetCapturedString(); +std::string GetCapturedStream(CapturedStream** captured_stream) { + const std::string content = (*captured_stream)->GetCapturedString(); delete *captured_stream; *captured_stream = NULL; @@ -622,21 +1044,79 @@ void CaptureStderr() { } // Stops capturing stdout and returns the captured string. -String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } +std::string GetCapturedStdout() { + return GetCapturedStream(&g_captured_stdout); +} // Stops capturing stderr and returns the captured string. -String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } +std::string GetCapturedStderr() { + return GetCapturedStream(&g_captured_stderr); +} #endif // GTEST_HAS_STREAM_REDIRECTION +std::string TempDir() { +#if GTEST_OS_WINDOWS_MOBILE + return "\\temp\\"; +#elif GTEST_OS_WINDOWS + const char* temp_dir = posix::GetEnv("TEMP"); + if (temp_dir == NULL || temp_dir[0] == '\0') + return "\\temp\\"; + else if (temp_dir[strlen(temp_dir) - 1] == '\\') + return temp_dir; + else + return std::string(temp_dir) + "\\"; +#elif GTEST_OS_LINUX_ANDROID + return "/sdcard/"; +#else + return "/tmp/"; +#endif // GTEST_OS_WINDOWS_MOBILE +} + +size_t GetFileSize(FILE* file) { + fseek(file, 0, SEEK_END); + return static_cast<size_t>(ftell(file)); +} + +std::string ReadEntireFile(FILE* file) { + const size_t file_size = GetFileSize(file); + char* const buffer = new char[file_size]; + + size_t bytes_last_read = 0; // # of bytes read in the last fread() + size_t bytes_read = 0; // # of bytes read so far + + fseek(file, 0, SEEK_SET); + + // Keeps reading the file until we cannot read further or the + // pre-determined file size is reached. + do { + bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); + bytes_read += bytes_last_read; + } while (bytes_last_read > 0 && bytes_read < file_size); + + const std::string content(buffer, bytes_read); + delete[] buffer; + + return content; +} + #if GTEST_HAS_DEATH_TEST -// A copy of all command line arguments. Set by InitGoogleTest(). -::std::vector<String> g_argvs; +static const ::std::vector<testing::internal::string>* g_injected_test_argvs = + NULL; // Owned. -// Returns the command line as a vector of strings. -const ::std::vector<String>& GetArgvs() { return g_argvs; } +void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) { + if (g_injected_test_argvs != argvs) + delete g_injected_test_argvs; + g_injected_test_argvs = argvs; +} +const ::std::vector<testing::internal::string>& GetInjectableArgvs() { + if (g_injected_test_argvs != NULL) { + return *g_injected_test_argvs; + } + return GetArgvs(); +} #endif // GTEST_HAS_DEATH_TEST #if GTEST_OS_WINDOWS_MOBILE @@ -651,8 +1131,8 @@ void Abort() { // Returns the name of the environment variable corresponding to the // given flag. For example, FlagToEnvVar("foo") will return // "GTEST_FOO" in the open-source version. -static String FlagToEnvVar(const char* flag) { - const String full_flag = +static std::string FlagToEnvVar(const char* flag) { + const std::string full_flag = (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); Message env_var; @@ -709,7 +1189,10 @@ bool ParseInt32(const Message& src_text, const char* str, Int32* value) { // // The value is considered true iff it's not "0". bool BoolFromGTestEnv(const char* flag, bool default_value) { - const String env_var = FlagToEnvVar(flag); +#if defined(GTEST_GET_BOOL_FROM_ENV_) + return GTEST_GET_BOOL_FROM_ENV_(flag, default_value); +#endif // defined(GTEST_GET_BOOL_FROM_ENV_) + const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); return string_value == NULL ? default_value : strcmp(string_value, "0") != 0; @@ -719,7 +1202,10 @@ bool BoolFromGTestEnv(const char* flag, bool default_value) { // variable corresponding to the given flag; if it isn't set or // doesn't represent a valid 32-bit integer, returns default_value. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { - const String env_var = FlagToEnvVar(flag); +#if defined(GTEST_GET_INT32_FROM_ENV_) + return GTEST_GET_INT32_FROM_ENV_(flag, default_value); +#endif // defined(GTEST_GET_INT32_FROM_ENV_) + const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); if (string_value == NULL) { // The environment variable is not set. @@ -740,25 +1226,34 @@ Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { // Reads and returns the string environment variable corresponding to // the given flag; if it's not set, returns default_value. -const char* StringFromGTestEnv(const char* flag, const char* default_value) { - const String env_var = FlagToEnvVar(flag); - const char* const value = posix::GetEnv(env_var.c_str()); - return value == NULL ? default_value : value; -} +std::string StringFromGTestEnv(const char* flag, const char* default_value) { +#if defined(GTEST_GET_STRING_FROM_ENV_) + return GTEST_GET_STRING_FROM_ENV_(flag, default_value); +#endif // defined(GTEST_GET_STRING_FROM_ENV_) + const std::string env_var = FlagToEnvVar(flag); + const char* value = posix::GetEnv(env_var.c_str()); + if (value != NULL) { + return value; + } -// Pin the vtables to this file. -#if GTEST_HAS_PTHREAD -ThreadWithParamBase::~ThreadWithParamBase() {} -ThreadLocalValueHolderBase::~ThreadLocalValueHolderBase() {} -#endif -TestFactoryBase::~TestFactoryBase() {} + // As a special case for the 'output' flag, if GTEST_OUTPUT is not + // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build + // system. The value of XML_OUTPUT_FILE is a filename without the + // "xml:" prefix of GTEST_OUTPUT. + // + // The net priority order after flag processing is thus: + // --gtest_output command line flag + // GTEST_OUTPUT environment variable + // XML_OUTPUT_FILE environment variable + // 'default_value' + if (strcmp(flag, "output") == 0) { + value = posix::GetEnv("XML_OUTPUT_FILE"); + if (value != NULL) { + return std::string("xml:") + value; + } + } + return default_value; +} } // namespace internal } // namespace testing - -// Pin the vtable to this file. -#if !GTEST_NO_LLVM_RAW_OSTREAM -namespace llvm { -void convertible_fwd_ostream::anchor() {} -} -#endif diff --git a/gnu/llvm/utils/unittest/googletest/src/gtest-printers.cc b/gnu/llvm/utils/unittest/googletest/src/gtest-printers.cc index 205a39425f0..a2df412f8a2 100644 --- a/gnu/llvm/utils/unittest/googletest/src/gtest-printers.cc +++ b/gnu/llvm/utils/unittest/googletest/src/gtest-printers.cc @@ -45,6 +45,7 @@ #include "gtest/gtest-printers.h" #include <ctype.h> #include <stdio.h> +#include <cwchar> #include <ostream> // NOLINT #include <string> #include "gtest/internal/gtest-port.h" @@ -55,15 +56,10 @@ namespace { using ::std::ostream; -#if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s. -# define snprintf _snprintf -#elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf. -# define snprintf _snprintf_s -#elif _MSC_VER -# define snprintf _snprintf -#endif // GTEST_OS_WINDOWS_MOBILE - // Prints a segment of bytes in the given object. +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, size_t count, ostream* os) { char text[5] = ""; @@ -77,7 +73,7 @@ void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, else *os << '-'; } - snprintf(text, sizeof(text), "%02X", obj_bytes[j]); + GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]); *os << text; } } @@ -127,7 +123,7 @@ namespace internal { // Depending on the value of a char (or wchar_t), we print it in one // of three formats: // - as is if it's a printable ASCII (e.g. 'a', '2', ' '), -// - as a hexadecimal escape sequence (e.g. '\x7F'), or +// - as a hexidecimal escape sequence (e.g. '\x7F'), or // - as a special escape sequence (e.g. '\r', '\n'). enum CharFormat { kAsIs, @@ -184,16 +180,16 @@ static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { *os << static_cast<char>(c); return kAsIs; } else { - *os << String::Format("\\x%X", static_cast<UnsignedChar>(c)); + *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c)); return kHexEscape; } } return kSpecialEscape; } -// Prints a char c as if it's part of a string literal, escaping it when +// Prints a wchar_t c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. -static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) { +static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { switch (c) { case L'\'': *os << "'"; @@ -208,8 +204,9 @@ static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) { // Prints a char c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. -static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) { - return PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os); +static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { + return PrintAsStringLiteralTo( + static_cast<wchar_t>(static_cast<unsigned char>(c)), os); } // Prints a wide or narrow character c and its code. '\0' is printed @@ -228,16 +225,15 @@ void PrintCharAndCodeTo(Char c, ostream* os) { // obvious). if (c == 0) return; - *os << " (" << String::Format("%d", c).c_str(); + *os << " (" << static_cast<int>(c); - // For more convenience, we print c's code again in hexadecimal, + // For more convenience, we print c's code again in hexidecimal, // unless c was already printed in the form '\x##' or the code is in // [1, 9]. if (format == kHexEscape || (1 <= c && c <= 9)) { // Do nothing. } else { - *os << String::Format(", 0x%X", - static_cast<UnsignedChar>(c)).c_str(); + *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c)); } *os << ")"; } @@ -255,48 +251,69 @@ void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo<wchar_t>(wc, os); } -// Prints the given array of characters to the ostream. -// The array starts at *begin, the length is len, it may include '\0' characters -// and may not be null-terminated. -static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) { - *os << "\""; +// Prints the given array of characters to the ostream. CharType must be either +// char or wchar_t. +// The array starts at begin, the length is len, it may include '\0' characters +// and may not be NUL-terminated. +template <typename CharType> +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +static void PrintCharsAsStringTo( + const CharType* begin, size_t len, ostream* os) { + const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; + *os << kQuoteBegin; bool is_previous_hex = false; for (size_t index = 0; index < len; ++index) { - const char cur = begin[index]; + const CharType cur = begin[index]; if (is_previous_hex && IsXDigit(cur)) { // Previous character is of '\x..' form and this character can be // interpreted as another hexadecimal digit in its number. Break string to // disambiguate. - *os << "\" \""; + *os << "\" " << kQuoteBegin; } - is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape; + is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; } *os << "\""; } +// Prints a (const) char/wchar_t array of 'len' elements, starting at address +// 'begin'. CharType must be either char or wchar_t. +template <typename CharType> +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +static void UniversalPrintCharArray( + const CharType* begin, size_t len, ostream* os) { + // The code + // const char kFoo[] = "foo"; + // generates an array of 4, not 3, elements, with the last one being '\0'. + // + // Therefore when printing a char array, we don't print the last element if + // it's '\0', such that the output matches the string literal as it's + // written in the source code. + if (len > 0 && begin[len - 1] == '\0') { + PrintCharsAsStringTo(begin, len - 1, os); + return; + } + + // If, however, the last element in the array is not '\0', e.g. + // const char kFoo[] = { 'f', 'o', 'o' }; + // we must print the entire array. We also print a message to indicate + // that the array is not NUL-terminated. + PrintCharsAsStringTo(begin, len, os); + *os << " (no terminating NUL)"; +} + // Prints a (const) char array of 'len' elements, starting at address 'begin'. void UniversalPrintArray(const char* begin, size_t len, ostream* os) { - PrintCharsAsStringTo(begin, len, os); + UniversalPrintCharArray(begin, len, os); } -// Prints the given array of wide characters to the ostream. -// The array starts at *begin, the length is len, it may include L'\0' -// characters and may not be null-terminated. -static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len, - ostream* os) { - *os << "L\""; - bool is_previous_hex = false; - for (size_t index = 0; index < len; ++index) { - const wchar_t cur = begin[index]; - if (is_previous_hex && isascii(cur) && IsXDigit(static_cast<char>(cur))) { - // Previous character is of '\x..' form and this character can be - // interpreted as another hexadecimal digit in its number. Break string to - // disambiguate. - *os << "\" L\""; - } - is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape; - } - *os << "\""; +// Prints a (const) wchar_t array of 'len' elements, starting at address +// 'begin'. +void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { + UniversalPrintCharArray(begin, len, os); } // Prints the given C string to the ostream. @@ -322,7 +339,7 @@ void PrintTo(const wchar_t* s, ostream* os) { *os << "NULL"; } else { *os << ImplicitCast_<const void*>(s) << " pointing to "; - PrintWideCharsAsStringTo(s, wcslen(s), os); + PrintCharsAsStringTo(s, std::wcslen(s), os); } } #endif // wchar_t is native @@ -341,13 +358,13 @@ void PrintStringTo(const ::std::string& s, ostream* os) { // Prints a ::wstring object. #if GTEST_HAS_GLOBAL_WSTRING void PrintWideStringTo(const ::wstring& s, ostream* os) { - PrintWideCharsAsStringTo(s.data(), s.size(), os); + PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_GLOBAL_WSTRING #if GTEST_HAS_STD_WSTRING void PrintWideStringTo(const ::std::wstring& s, ostream* os) { - PrintWideCharsAsStringTo(s.data(), s.size(), os); + PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_STD_WSTRING diff --git a/gnu/llvm/utils/unittest/googletest/src/gtest-test-part.cc b/gnu/llvm/utils/unittest/googletest/src/gtest-test-part.cc index 5ddc67c1c9e..fb0e35425e1 100644 --- a/gnu/llvm/utils/unittest/googletest/src/gtest-test-part.cc +++ b/gnu/llvm/utils/unittest/googletest/src/gtest-test-part.cc @@ -35,9 +35,9 @@ // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. +// included, or there will be a compiler error. This trick exists to +// prevent the accidental inclusion of gtest-internal-inl.h in the +// user's code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ @@ -48,10 +48,10 @@ using internal::GetUnitTestImpl; // Gets the summary of the failure message by omitting the stack trace // in it. -internal::String TestPartResult::ExtractSummary(const char* message) { +std::string TestPartResult::ExtractSummary(const char* message) { const char* const stack_trace = strstr(message, internal::kStackTraceMarker); - return stack_trace == NULL ? internal::String(message) : - internal::String(message, stack_trace - message); + return stack_trace == NULL ? message : + std::string(message, stack_trace); } // Prints a TestPartResult object. diff --git a/gnu/llvm/utils/unittest/googletest/src/gtest-typed-test.cc b/gnu/llvm/utils/unittest/googletest/src/gtest-typed-test.cc index a5cc88f9205..df1eef4754e 100644 --- a/gnu/llvm/utils/unittest/googletest/src/gtest-typed-test.cc +++ b/gnu/llvm/utils/unittest/googletest/src/gtest-typed-test.cc @@ -45,33 +45,41 @@ static const char* SkipSpaces(const char* str) { return str; } +static std::vector<std::string> SplitIntoTestNames(const char* src) { + std::vector<std::string> name_vec; + src = SkipSpaces(src); + for (; src != NULL; src = SkipComma(src)) { + name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src))); + } + return name_vec; +} + // Verifies that registered_tests match the test names in -// defined_test_names_; returns registered_tests if successful, or +// registered_tests_; returns registered_tests if successful, or // aborts the program otherwise. const char* TypedTestCasePState::VerifyRegisteredTestNames( const char* file, int line, const char* registered_tests) { - typedef ::std::set<const char*>::const_iterator DefinedTestIter; + typedef RegisteredTestsMap::const_iterator RegisteredTestIter; registered_ = true; - // Skip initial whitespace in registered_tests since some - // preprocessors prefix stringizied literals with whitespace. - registered_tests = SkipSpaces(registered_tests); + std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests); Message errors; - ::std::set<String> tests; - for (const char* names = registered_tests; names != NULL; - names = SkipComma(names)) { - const String name = GetPrefixUntilComma(names); + + std::set<std::string> tests; + for (std::vector<std::string>::const_iterator name_it = name_vec.begin(); + name_it != name_vec.end(); ++name_it) { + const std::string& name = *name_it; if (tests.count(name) != 0) { errors << "Test " << name << " is listed more than once.\n"; continue; } bool found = false; - for (DefinedTestIter it = defined_test_names_.begin(); - it != defined_test_names_.end(); + for (RegisteredTestIter it = registered_tests_.begin(); + it != registered_tests_.end(); ++it) { - if (name == *it) { + if (name == it->first) { found = true; break; } @@ -85,15 +93,15 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames( } } - for (DefinedTestIter it = defined_test_names_.begin(); - it != defined_test_names_.end(); + for (RegisteredTestIter it = registered_tests_.begin(); + it != registered_tests_.end(); ++it) { - if (tests.count(*it) == 0) { - errors << "You forgot to list test " << *it << ".\n"; + if (tests.count(it->first) == 0) { + errors << "You forgot to list test " << it->first << ".\n"; } } - const String& errors_str = errors.GetString(); + const std::string& errors_str = errors.GetString(); if (errors_str != "") { fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), errors_str.c_str()); diff --git a/gnu/llvm/utils/unittest/googletest/src/gtest.cc b/gnu/llvm/utils/unittest/googletest/src/gtest.cc index 57807646ea1..d882ab2e36a 100644 --- a/gnu/llvm/utils/unittest/googletest/src/gtest.cc +++ b/gnu/llvm/utils/unittest/googletest/src/gtest.cc @@ -32,6 +32,7 @@ // The Google C++ Testing Framework (Google Test) #include "gtest/gtest.h" +#include "gtest/internal/custom/gtest.h" #include "gtest/gtest-spi.h" #include <ctype.h> @@ -39,10 +40,15 @@ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> +#include <time.h> #include <wchar.h> #include <wctype.h> #include <algorithm> +#include <iomanip> +#include <limits> +#include <list> +#include <map> #include <ostream> // NOLINT #include <sstream> #include <vector> @@ -77,6 +83,7 @@ #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. # include <windows.h> // NOLINT +# undef min #elif GTEST_OS_WINDOWS // We are on Windows proper. @@ -99,6 +106,7 @@ // cpplint thinks that the header is already included, so we want to // silence it. # include <windows.h> // NOLINT +# undef min #else @@ -121,6 +129,8 @@ #if GTEST_CAN_STREAM_RESULTS_ # include <arpa/inet.h> // NOLINT # include <netdb.h> // NOLINT +# include <sys/socket.h> // NOLINT +# include <sys/types.h> // NOLINT #endif // Indicates that this translation unit is part of Google Test's @@ -179,6 +189,16 @@ bool g_help_flag = false; } // namespace internal +static const char* GetDefaultFilter() { +#ifdef GTEST_TEST_FILTER_ENV_VAR_ + const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_); + if (testbridge_test_only != NULL) { + return testbridge_test_only; + } +#endif // GTEST_TEST_FILTER_ENV_VAR_ + return kUniversalFilter; +} + GTEST_DEFINE_bool_( also_run_disabled_tests, internal::BoolFromGTestEnv("also_run_disabled_tests", false), @@ -201,11 +221,11 @@ GTEST_DEFINE_string_( "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " - "is set to xterm, xterm-color, xterm-256color, linux or cygwin."); + "is set to a terminal type that supports colors."); GTEST_DEFINE_string_( filter, - internal::StringFromGTestEnv("filter", kUniversalFilter), + internal::StringFromGTestEnv("filter", GetDefaultFilter()), "A colon-separated list of glob (not regex) patterns " "for filtering the tests to run, optionally followed by a " "'-' and a : separated list of negative patterns (tests to " @@ -276,6 +296,13 @@ GTEST_DEFINE_bool_( "if exceptions are enabled or exit the program with a non-zero code " "otherwise."); +#if GTEST_USE_OWN_FLAGFILE_FLAG_ +GTEST_DEFINE_string_( + flagfile, + internal::StringFromGTestEnv("flagfile", ""), + "This flag specifies the flagfile to read command-line flags from."); +#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ + namespace internal { // Generates a random number from [0, range), using a Linear @@ -300,13 +327,7 @@ UInt32 Random::Generate(UInt32 range) { // GTestIsInitialized() returns true iff the user has initialized // Google Test. Useful for catching the user mistake of not initializing // Google Test before calling RUN_ALL_TESTS(). -// -// A user must call testing::InitGoogleTest() to initialize Google -// Test. g_init_gtest_count is set to the number of times -// InitGoogleTest() has been called. We don't protect this variable -// under a mutex as it is only accessed in the main thread. -int g_init_gtest_count = 0; -static bool GTestIsInitialized() { return g_init_gtest_count != 0; } +static bool GTestIsInitialized() { return GetArgvs().size() > 0; } // Iterates over a vector of TestCases, keeping a running sum of the // results of calling a given int-returning method on each. @@ -360,10 +381,18 @@ void AssertHelper::operator=(const Message& message) const { } // Mutex for linked pointers. -GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); +GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); -// Application pathname gotten in InitGoogleTest. -String g_executable_path; +// A copy of all command line arguments. Set by InitGoogleTest(). +::std::vector<testing::internal::string> g_argvs; + +const ::std::vector<testing::internal::string>& GetArgvs() { +#if defined(GTEST_CUSTOM_GET_ARGVS_) + return GTEST_CUSTOM_GET_ARGVS_(); +#else // defined(GTEST_CUSTOM_GET_ARGVS_) + return g_argvs; +#endif // defined(GTEST_CUSTOM_GET_ARGVS_) +} // Returns the current application's name, removing directory path if that // is present. @@ -371,9 +400,9 @@ FilePath GetCurrentExecutableName() { FilePath result; #if GTEST_OS_WINDOWS - result.Set(FilePath(g_executable_path).RemoveExtension("exe")); + result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); #else - result.Set(FilePath(g_executable_path)); + result.Set(FilePath(GetArgvs()[0])); #endif // GTEST_OS_WINDOWS return result.RemoveDirectoryName(); @@ -382,29 +411,29 @@ FilePath GetCurrentExecutableName() { // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. -String UnitTestOptions::GetOutputFormat() { +std::string UnitTestOptions::GetOutputFormat() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); - if (gtest_output_flag == NULL) return String(""); + if (gtest_output_flag == NULL) return std::string(""); const char* const colon = strchr(gtest_output_flag, ':'); return (colon == NULL) ? - String(gtest_output_flag) : - String(gtest_output_flag, colon - gtest_output_flag); + std::string(gtest_output_flag) : + std::string(gtest_output_flag, colon - gtest_output_flag); } // Returns the name of the requested output file, or the default if none // was explicitly specified. -String UnitTestOptions::GetAbsolutePathToOutputFile() { +std::string UnitTestOptions::GetAbsolutePathToOutputFile() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); if (gtest_output_flag == NULL) - return String(""); + return ""; const char* const colon = strchr(gtest_output_flag, ':'); if (colon == NULL) - return String(internal::FilePath::ConcatPaths( - internal::FilePath( - UnitTest::GetInstance()->original_working_dir()), - internal::FilePath(kDefaultOutputFile)).ToString() ); + return internal::FilePath::ConcatPaths( + internal::FilePath( + UnitTest::GetInstance()->original_working_dir()), + internal::FilePath(kDefaultOutputFile)).string(); internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) @@ -417,12 +446,12 @@ String UnitTestOptions::GetAbsolutePathToOutputFile() { internal::FilePath(colon + 1)); if (!output_name.IsDirectory()) - return output_name.ToString(); + return output_name.string(); internal::FilePath result(internal::FilePath::GenerateUniqueFileName( output_name, internal::GetCurrentExecutableName(), GetOutputFormat().c_str())); - return result.ToString(); + return result.string(); } // Returns true iff the wildcard pattern matches the string. The @@ -447,7 +476,8 @@ bool UnitTestOptions::PatternMatchesString(const char *pattern, } } -bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) { +bool UnitTestOptions::MatchesFilter( + const std::string& name, const char* filter) { const char *cur_pattern = filter; for (;;) { if (PatternMatchesString(cur_pattern, name.c_str())) { @@ -467,28 +497,24 @@ bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) { } } -// TODO(keithray): move String function implementations to gtest-string.cc. - // Returns true iff the user-specified filter matches the test case // name and the test name. -bool UnitTestOptions::FilterMatchesTest(const String &test_case_name, - const String &test_name) { - const String& full_name = String::Format("%s.%s", - test_case_name.c_str(), - test_name.c_str()); +bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name, + const std::string &test_name) { + const std::string& full_name = test_case_name + "." + test_name.c_str(); // Split --gtest_filter at '-', if there is one, to separate into // positive filter and negative filter portions const char* const p = GTEST_FLAG(filter).c_str(); const char* const dash = strchr(p, '-'); - String positive; - String negative; + std::string positive; + std::string negative; if (dash == NULL) { positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter - negative = String(""); + negative = ""; } else { - positive = String(p, dash - p); // Everything up to the dash - negative = String(dash+1); // Everything after the dash + positive = std::string(p, dash); // Everything up to the dash + negative = std::string(dash + 1); // Everything after the dash if (positive.empty()) { // Treat '-test1' as the same as '*-test1' positive = kUniversalFilter; @@ -597,7 +623,7 @@ TypeId GetTestTypeId() { // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). -const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); +extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); // This predicate-formatter checks that 'results' contains a test part // failure of the given type and that the failure message contains the @@ -608,7 +634,7 @@ AssertionResult HasOneFailure(const char* /* results_expr */, const TestPartResultArray& results, TestPartResult::Type type, const string& substr) { - const String expected(type == TestPartResult::kFatalFailure ? + const std::string expected(type == TestPartResult::kFatalFailure ? "1 fatal failure" : "1 non-fatal failure"); Message msg; @@ -731,11 +757,22 @@ int UnitTestImpl::failed_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); } +// Gets the number of disabled tests that will be reported in the XML report. +int UnitTestImpl::reportable_disabled_test_count() const { + return SumOverTestCaseList(test_cases_, + &TestCase::reportable_disabled_test_count); +} + // Gets the number of disabled tests. int UnitTestImpl::disabled_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); } +// Gets the number of tests to be printed in the XML report. +int UnitTestImpl::reportable_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count); +} + // Gets the number of all tests. int UnitTestImpl::total_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); @@ -746,7 +783,7 @@ int UnitTestImpl::test_to_run_count() const { return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); } -// Returns the current OS stack trace as a String. +// Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter @@ -756,9 +793,13 @@ int UnitTestImpl::test_to_run_count() const { // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. -String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { - (void)skip_count; - return String(""); +std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { + return os_stack_trace_getter()->CurrentStackTrace( + static_cast<int>(GTEST_FLAG(stack_trace_depth)), + skip_count + 1 + // Skips the user-specified number of frames plus this function + // itself. + ); // NOLINT } // Returns the current time in milliseconds. @@ -787,21 +828,13 @@ TimeInMillis GetTimeInMillis() { #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ __timeb64 now; -# ifdef _MSC_VER - // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 // (deprecated function) there. // TODO(kenton@google.com): Use GetTickCount()? Or use // SystemTimeToFileTime() -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4996) // Temporarily disables warning 4996. - _ftime64(&now); -# pragma warning(pop) // Restores the warning state. -# else - + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) _ftime64(&now); - -# endif // _MSC_VER + GTEST_DISABLE_MSC_WARNINGS_POP_() return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm; #elif GTEST_HAS_GETTIMEOFDAY_ @@ -815,41 +848,7 @@ TimeInMillis GetTimeInMillis() { // Utilities -// class String - -// Returns the input enclosed in double quotes if it's not NULL; -// otherwise returns "(null)". For example, "\"Hello\"" is returned -// for input "Hello". -// -// This is useful for printing a C string in the syntax of a literal. -// -// Known issue: escape sequences are not handled yet. -String String::ShowCStringQuoted(const char* c_str) { - return c_str ? String::Format("\"%s\"", c_str) : String("(null)"); -} - -// Copies at most length characters from str into a newly-allocated -// piece of memory of size length+1. The memory is allocated with new[]. -// A terminating null byte is written to the memory, and a pointer to it -// is returned. If str is NULL, NULL is returned. -static char* CloneString(const char* str, size_t length) { - if (str == NULL) { - return NULL; - } else { - char* const clone = new char[length + 1]; - posix::StrNCpy(clone, str, length); - clone[length] = '\0'; - return clone; - } -} - -// Clones a 0-terminated C string, allocating memory using new. The -// caller is responsible for deleting[] the return value. Returns the -// cloned string, or NULL if the input is NULL. -const char * String::CloneCString(const char* c_str) { - return (c_str == NULL) ? - NULL : CloneString(c_str, strlen(c_str)); -} +// class String. #if GTEST_OS_WINDOWS_MOBILE // Creates a UTF-16 wide string from the given ANSI string, allocating @@ -906,11 +905,6 @@ bool String::CStringEquals(const char * lhs, const char * rhs) { // encoding, and streams the result to the given Message object. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, Message* msg) { - // TODO(wan): consider allowing a testing::String object to - // contain '\0'. This will make it behave more like std::string, - // and will allow ToUtf8String() to return the correct encoding - // for '\0' s.t. we can get rid of the conditional here (and in - // several other places). for (size_t i = 0; i != length; ) { // NOLINT if (wstr[i] != L'\0') { *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); @@ -925,8 +919,45 @@ static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING +void SplitString(const ::std::string& str, char delimiter, + ::std::vector< ::std::string>* dest) { + ::std::vector< ::std::string> parsed; + ::std::string::size_type pos = 0; + while (::testing::internal::AlwaysTrue()) { + const ::std::string::size_type colon = str.find(delimiter, pos); + if (colon == ::std::string::npos) { + parsed.push_back(str.substr(pos)); + break; + } else { + parsed.push_back(str.substr(pos, colon - pos)); + pos = colon + 1; + } + } + dest->swap(parsed); +} + } // namespace internal +// Constructs an empty Message. +// We allocate the stringstream separately because otherwise each use of +// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's +// stack frame leading to huge stack frames in some cases; gcc does not reuse +// the stack space. +Message::Message() : ss_(new ::std::stringstream) { + // By default, we want there to be enough precision when printing + // a double to a Message. + *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2); +} + +// These two overloads allow streaming a wide C string to a Message +// using the UTF-8 encoding. +Message& Message::operator <<(const wchar_t* wide_c_str) { + return *this << internal::String::ShowWideCString(wide_c_str); +} +Message& Message::operator <<(wchar_t* wide_c_str) { + return *this << internal::String::ShowWideCString(wide_c_str); +} + #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. @@ -945,6 +976,12 @@ Message& Message::operator <<(const ::wstring& wstr) { } #endif // GTEST_HAS_GLOBAL_WSTRING +// Gets the text streamed to this object so far as an std::string. +// Each '\0' character in the buffer is replaced with "\\0". +std::string Message::GetString() const { + return internal::StringStreamToString(ss_.get()); +} + // AssertionResult constructors. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult::AssertionResult(const AssertionResult& other) @@ -954,6 +991,13 @@ AssertionResult::AssertionResult(const AssertionResult& other) static_cast< ::std::string*>(NULL)) { } +// Swaps two AssertionResults. +void AssertionResult::swap(AssertionResult& other) { + using std::swap; + swap(success_, other.success_); + swap(message_, other.message_); +} + // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult AssertionResult::operator!() const { AssertionResult negation(!success_); @@ -980,6 +1024,276 @@ AssertionResult AssertionFailure(const Message& message) { namespace internal { +namespace edit_distance { +std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left, + const std::vector<size_t>& right) { + std::vector<std::vector<double> > costs( + left.size() + 1, std::vector<double>(right.size() + 1)); + std::vector<std::vector<EditType> > best_move( + left.size() + 1, std::vector<EditType>(right.size() + 1)); + + // Populate for empty right. + for (size_t l_i = 0; l_i < costs.size(); ++l_i) { + costs[l_i][0] = static_cast<double>(l_i); + best_move[l_i][0] = kRemove; + } + // Populate for empty left. + for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) { + costs[0][r_i] = static_cast<double>(r_i); + best_move[0][r_i] = kAdd; + } + + for (size_t l_i = 0; l_i < left.size(); ++l_i) { + for (size_t r_i = 0; r_i < right.size(); ++r_i) { + if (left[l_i] == right[r_i]) { + // Found a match. Consume it. + costs[l_i + 1][r_i + 1] = costs[l_i][r_i]; + best_move[l_i + 1][r_i + 1] = kMatch; + continue; + } + + const double add = costs[l_i + 1][r_i]; + const double remove = costs[l_i][r_i + 1]; + const double replace = costs[l_i][r_i]; + if (add < remove && add < replace) { + costs[l_i + 1][r_i + 1] = add + 1; + best_move[l_i + 1][r_i + 1] = kAdd; + } else if (remove < add && remove < replace) { + costs[l_i + 1][r_i + 1] = remove + 1; + best_move[l_i + 1][r_i + 1] = kRemove; + } else { + // We make replace a little more expensive than add/remove to lower + // their priority. + costs[l_i + 1][r_i + 1] = replace + 1.00001; + best_move[l_i + 1][r_i + 1] = kReplace; + } + } + } + + // Reconstruct the best path. We do it in reverse order. + std::vector<EditType> best_path; + for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) { + EditType move = best_move[l_i][r_i]; + best_path.push_back(move); + l_i -= move != kAdd; + r_i -= move != kRemove; + } + std::reverse(best_path.begin(), best_path.end()); + return best_path; +} + +namespace { + +// Helper class to convert string into ids with deduplication. +class InternalStrings { + public: + size_t GetId(const std::string& str) { + IdMap::iterator it = ids_.find(str); + if (it != ids_.end()) return it->second; + size_t id = ids_.size(); + return ids_[str] = id; + } + + private: + typedef std::map<std::string, size_t> IdMap; + IdMap ids_; +}; + +} // namespace + +std::vector<EditType> CalculateOptimalEdits( + const std::vector<std::string>& left, + const std::vector<std::string>& right) { + std::vector<size_t> left_ids, right_ids; + { + InternalStrings intern_table; + for (size_t i = 0; i < left.size(); ++i) { + left_ids.push_back(intern_table.GetId(left[i])); + } + for (size_t i = 0; i < right.size(); ++i) { + right_ids.push_back(intern_table.GetId(right[i])); + } + } + return CalculateOptimalEdits(left_ids, right_ids); +} + +namespace { + +// Helper class that holds the state for one hunk and prints it out to the +// stream. +// It reorders adds/removes when possible to group all removes before all +// adds. It also adds the hunk header before printint into the stream. +class Hunk { + public: + Hunk(size_t left_start, size_t right_start) + : left_start_(left_start), + right_start_(right_start), + adds_(), + removes_(), + common_() {} + + void PushLine(char edit, const char* line) { + switch (edit) { + case ' ': + ++common_; + FlushEdits(); + hunk_.push_back(std::make_pair(' ', line)); + break; + case '-': + ++removes_; + hunk_removes_.push_back(std::make_pair('-', line)); + break; + case '+': + ++adds_; + hunk_adds_.push_back(std::make_pair('+', line)); + break; + } + } + + void PrintTo(std::ostream* os) { + PrintHeader(os); + FlushEdits(); + for (std::list<std::pair<char, const char*> >::const_iterator it = + hunk_.begin(); + it != hunk_.end(); ++it) { + *os << it->first << it->second << "\n"; + } + } + + bool has_edits() const { return adds_ || removes_; } + + private: + void FlushEdits() { + hunk_.splice(hunk_.end(), hunk_removes_); + hunk_.splice(hunk_.end(), hunk_adds_); + } + + // Print a unified diff header for one hunk. + // The format is + // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@" + // where the left/right parts are ommitted if unnecessary. + void PrintHeader(std::ostream* ss) const { + *ss << "@@ "; + if (removes_) { + *ss << "-" << left_start_ << "," << (removes_ + common_); + } + if (removes_ && adds_) { + *ss << " "; + } + if (adds_) { + *ss << "+" << right_start_ << "," << (adds_ + common_); + } + *ss << " @@\n"; + } + + size_t left_start_, right_start_; + size_t adds_, removes_, common_; + std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_; +}; + +} // namespace + +// Create a list of diff hunks in Unified diff format. +// Each hunk has a header generated by PrintHeader above plus a body with +// lines prefixed with ' ' for no change, '-' for deletion and '+' for +// addition. +// 'context' represents the desired unchanged prefix/suffix around the diff. +// If two hunks are close enough that their contexts overlap, then they are +// joined into one hunk. +std::string CreateUnifiedDiff(const std::vector<std::string>& left, + const std::vector<std::string>& right, + size_t context) { + const std::vector<EditType> edits = CalculateOptimalEdits(left, right); + + size_t l_i = 0, r_i = 0, edit_i = 0; + std::stringstream ss; + while (edit_i < edits.size()) { + // Find first edit. + while (edit_i < edits.size() && edits[edit_i] == kMatch) { + ++l_i; + ++r_i; + ++edit_i; + } + + // Find the first line to include in the hunk. + const size_t prefix_context = std::min(l_i, context); + Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1); + for (size_t i = prefix_context; i > 0; --i) { + hunk.PushLine(' ', left[l_i - i].c_str()); + } + + // Iterate the edits until we found enough suffix for the hunk or the input + // is over. + size_t n_suffix = 0; + for (; edit_i < edits.size(); ++edit_i) { + if (n_suffix >= context) { + // Continue only if the next hunk is very close. + std::vector<EditType>::const_iterator it = edits.begin() + edit_i; + while (it != edits.end() && *it == kMatch) ++it; + if (it == edits.end() || (it - edits.begin()) - edit_i >= context) { + // There is no next edit or it is too far away. + break; + } + } + + EditType edit = edits[edit_i]; + // Reset count when a non match is found. + n_suffix = edit == kMatch ? n_suffix + 1 : 0; + + if (edit == kMatch || edit == kRemove || edit == kReplace) { + hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str()); + } + if (edit == kAdd || edit == kReplace) { + hunk.PushLine('+', right[r_i].c_str()); + } + + // Advance indices, depending on edit type. + l_i += edit != kAdd; + r_i += edit != kRemove; + } + + if (!hunk.has_edits()) { + // We are done. We don't want this hunk. + break; + } + + hunk.PrintTo(&ss); + } + return ss.str(); +} + +} // namespace edit_distance + +namespace { + +// The string representation of the values received in EqFailure() are already +// escaped. Split them on escaped '\n' boundaries. Leave all other escaped +// characters the same. +std::vector<std::string> SplitEscapedString(const std::string& str) { + std::vector<std::string> lines; + size_t start = 0, end = str.size(); + if (end > 2 && str[0] == '"' && str[end - 1] == '"') { + ++start; + --end; + } + bool escaped = false; + for (size_t i = start; i + 1 < end; ++i) { + if (escaped) { + escaped = false; + if (str[i] == 'n') { + lines.push_back(str.substr(start, i - start - 1)); + start = i + 1; + } + } else { + escaped = str[i] == '\\'; + } + } + lines.push_back(str.substr(start, end - start)); + return lines; +} + +} // namespace + // Constructs and returns the message for an equality assertion // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // @@ -987,41 +1301,53 @@ namespace internal { // and their values, as strings. For example, for ASSERT_EQ(foo, bar) // where foo is 5 and bar is 6, we have: // -// expected_expression: "foo" -// actual_expression: "bar" -// expected_value: "5" -// actual_value: "6" +// lhs_expression: "foo" +// rhs_expression: "bar" +// lhs_value: "5" +// rhs_value: "6" // // The ignoring_case parameter is true iff the assertion is a -// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will +// *_STRCASEEQ*. When it's true, the string "Ignoring case" will // be inserted into the message. -AssertionResult EqFailure(const char* expected_expression, - const char* actual_expression, - const String& expected_value, - const String& actual_value, +AssertionResult EqFailure(const char* lhs_expression, + const char* rhs_expression, + const std::string& lhs_value, + const std::string& rhs_value, bool ignoring_case) { Message msg; - msg << "Value of: " << actual_expression; - if (actual_value != actual_expression) { - msg << "\n Actual: " << actual_value; + msg << " Expected: " << lhs_expression; + if (lhs_value != lhs_expression) { + msg << "\n Which is: " << lhs_value; + } + msg << "\nTo be equal to: " << rhs_expression; + if (rhs_value != rhs_expression) { + msg << "\n Which is: " << rhs_value; } - msg << "\nExpected: " << expected_expression; if (ignoring_case) { - msg << " (ignoring case)"; + msg << "\nIgnoring case"; } - if (expected_value != expected_expression) { - msg << "\nWhich is: " << expected_value; + + if (!lhs_value.empty() && !rhs_value.empty()) { + const std::vector<std::string> lhs_lines = + SplitEscapedString(lhs_value); + const std::vector<std::string> rhs_lines = + SplitEscapedString(rhs_value); + if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { + msg << "\nWith diff:\n" + << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); + } } return AssertionFailure() << msg; } // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. -String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value) { +std::string GetBoolAssertionFailureMessage( + const AssertionResult& assertion_result, + const char* expression_text, + const char* actual_predicate_value, + const char* expected_predicate_value) { const char* actual_message = assertion_result.message(); Message msg; msg << "Value of: " << expression_text @@ -1108,18 +1434,18 @@ namespace internal { // The helper function for {ASSERT|EXPECT}_EQ with int or enum // arguments. -AssertionResult CmpHelperEQ(const char* expected_expression, - const char* actual_expression, - BiggestInt expected, - BiggestInt actual) { - if (expected == actual) { +AssertionResult CmpHelperEQ(const char* lhs_expression, + const char* rhs_expression, + BiggestInt lhs, + BiggestInt rhs) { + if (lhs == rhs) { return AssertionSuccess(); } - return EqFailure(expected_expression, - actual_expression, - FormatForComparisonFailureMessage(expected, actual), - FormatForComparisonFailureMessage(actual, expected), + return EqFailure(lhs_expression, + rhs_expression, + FormatForComparisonFailureMessage(lhs, rhs), + FormatForComparisonFailureMessage(rhs, lhs), false); } @@ -1158,34 +1484,34 @@ GTEST_IMPL_CMP_HELPER_(GT, > ) #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. -AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual) { - if (String::CStringEquals(expected, actual)) { +AssertionResult CmpHelperSTREQ(const char* lhs_expression, + const char* rhs_expression, + const char* lhs, + const char* rhs) { + if (String::CStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(expected_expression, - actual_expression, - String::ShowCStringQuoted(expected), - String::ShowCStringQuoted(actual), + return EqFailure(lhs_expression, + rhs_expression, + PrintToString(lhs), + PrintToString(rhs), false); } // The helper function for {ASSERT|EXPECT}_STRCASEEQ. -AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual) { - if (String::CaseInsensitiveCStringEquals(expected, actual)) { +AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, + const char* rhs_expression, + const char* lhs, + const char* rhs) { + if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(expected_expression, - actual_expression, - String::ShowCStringQuoted(expected), - String::ShowCStringQuoted(actual), + return EqFailure(lhs_expression, + rhs_expression, + PrintToString(lhs), + PrintToString(rhs), true); } @@ -1349,7 +1675,7 @@ AssertionResult HRESULTFailureHelper(const char* expr, // want inserts expanded. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; - const DWORD kBufSize = 4096; // String::Format can't exceed this length. + const DWORD kBufSize = 4096; // Gets the system's human readable message string for this HRESULT. char error_text[kBufSize] = { '\0' }; DWORD message_length = ::FormatMessageA(kFlags, @@ -1359,7 +1685,7 @@ AssertionResult HRESULTFailureHelper(const char* expr, error_text, // output buffer kBufSize, // buf size NULL); // no arguments for inserts - // Trims tailing white space (FormatMessage leaves a trailing cr-lf) + // Trims tailing white space (FormatMessage leaves a trailing CR-LF) for (; message_length && IsSpace(error_text[message_length - 1]); --message_length) { error_text[message_length - 1] = '\0'; @@ -1367,10 +1693,10 @@ AssertionResult HRESULTFailureHelper(const char* expr, # endif // GTEST_OS_WINDOWS_MOBILE - const String error_hex(String::Format("0x%08X ", hr)); + const std::string error_hex("0x" + String::FormatHexInt(hr)); return ::testing::AssertionFailure() << "Expected: " << expr << " " << expected << ".\n" - << " Actual: " << error_hex << error_text << "\n"; + << " Actual: " << error_hex << " " << error_text << "\n"; } } // namespace @@ -1394,7 +1720,7 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT // Utility functions for encoding Unicode text (wide strings) in // UTF-8. -// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8 +// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 // like this: // // Code-point length Encoding @@ -1427,12 +1753,15 @@ inline UInt32 ChopLowBits(UInt32* bits, int n) { // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. -// The output buffer str must containt at least 32 characters. -// The function returns the address of the output buffer. // If the code_point is not a valid Unicode code point -// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output -// as '(Invalid Unicode 0xXXXXXXXX)'. -char* CodePointToUtf8(UInt32 code_point, char* str) { +// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted +// to "(Invalid Unicode 0xXXXXXXXX)". +std::string CodePointToUtf8(UInt32 code_point) { + if (code_point > kMaxCodePoint4) { + return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")"; + } + + char str[5]; // Big enough for the largest valid code point. if (code_point <= kMaxCodePoint1) { str[1] = '\0'; str[0] = static_cast<char>(code_point); // 0xxxxxxx @@ -1445,27 +1774,17 @@ char* CodePointToUtf8(UInt32 code_point, char* str) { str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx - } else if (code_point <= kMaxCodePoint4) { + } else { // code_point <= kMaxCodePoint4 str[4] = '\0'; str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx - } else { - // The longest string String::Format can produce when invoked - // with these parameters is 28 character long (not including - // the terminating nul character). We are asking for 32 character - // buffer just in case. This is also enough for strncpy to - // null-terminate the destination string. - posix::StrNCpy( - str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32); - str[31] = '\0'; // Makes sure no change in the format to strncpy leaves - // the result unterminated. } return str; } -// The following two functions only make sense if the system +// The following two functions only make sense if the the system // uses UTF-16 for wide string encoding. All supported systems // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. @@ -1501,7 +1820,7 @@ inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. -String WideStringToUtf8(const wchar_t* str, int num_chars) { +std::string WideStringToUtf8(const wchar_t* str, int num_chars) { if (num_chars == -1) num_chars = static_cast<int>(wcslen(str)); @@ -1519,27 +1838,17 @@ String WideStringToUtf8(const wchar_t* str, int num_chars) { unicode_code_point = static_cast<UInt32>(str[i]); } - char buffer[32]; // CodePointToUtf8 requires a buffer this big. - stream << CodePointToUtf8(unicode_code_point, buffer); + stream << CodePointToUtf8(unicode_code_point); } return StringStreamToString(&stream); } -// Converts a wide C string to a String using the UTF-8 encoding. +// Converts a wide C string to an std::string using the UTF-8 encoding. // NULL will be converted to "(null)". -String String::ShowWideCString(const wchar_t * wide_c_str) { - if (wide_c_str == NULL) return String("(null)"); - - return String(internal::WideStringToUtf8(wide_c_str, -1).c_str()); -} +std::string String::ShowWideCString(const wchar_t * wide_c_str) { + if (wide_c_str == NULL) return "(null)"; -// Similar to ShowWideCString(), except that this function encloses -// the converted string in double quotes. -String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) { - if (wide_c_str == NULL) return String("(null)"); - - return String::Format("L\"%s\"", - String::ShowWideCString(wide_c_str).c_str()); + return internal::WideStringToUtf8(wide_c_str, -1); } // Compares two wide C strings. Returns true iff they have the same @@ -1557,18 +1866,18 @@ bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { } // Helper function for *_STREQ on wide strings. -AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const wchar_t* expected, - const wchar_t* actual) { - if (String::WideCStringEquals(expected, actual)) { +AssertionResult CmpHelperSTREQ(const char* lhs_expression, + const char* rhs_expression, + const wchar_t* lhs, + const wchar_t* rhs) { + if (String::WideCStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(expected_expression, - actual_expression, - String::ShowWideCStringQuoted(expected), - String::ShowWideCStringQuoted(actual), + return EqFailure(lhs_expression, + rhs_expression, + PrintToString(lhs), + PrintToString(rhs), false); } @@ -1583,8 +1892,8 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: " - << String::ShowWideCStringQuoted(s1) - << " vs " << String::ShowWideCStringQuoted(s2); + << PrintToString(s1) + << " vs " << PrintToString(s2); } // Compares two C strings, ignoring case. Returns true iff they have @@ -1635,135 +1944,69 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, #endif // OS selector } -// Compares this with another String. -// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 -// if this is greater than rhs. -int String::Compare(const String & rhs) const { - const char* const lhs_c_str = c_str(); - const char* const rhs_c_str = rhs.c_str(); - - if (lhs_c_str == NULL) { - return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL - } else if (rhs_c_str == NULL) { - return 1; - } - - const size_t shorter_str_len = - length() <= rhs.length() ? length() : rhs.length(); - for (size_t i = 0; i != shorter_str_len; i++) { - if (lhs_c_str[i] < rhs_c_str[i]) { - return -1; - } else if (lhs_c_str[i] > rhs_c_str[i]) { - return 1; - } - } - return (length() < rhs.length()) ? -1 : - (length() > rhs.length()) ? 1 : 0; +// Returns true iff str ends with the given suffix, ignoring case. +// Any string is considered to end with an empty suffix. +bool String::EndsWithCaseInsensitive( + const std::string& str, const std::string& suffix) { + const size_t str_len = str.length(); + const size_t suffix_len = suffix.length(); + return (str_len >= suffix_len) && + CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, + suffix.c_str()); } -// Returns true iff this String ends with the given suffix. *Any* -// String is considered to end with a NULL or empty suffix. -bool String::EndsWith(const char* suffix) const { - if (suffix == NULL || CStringEquals(suffix, "")) return true; - - if (c_str() == NULL) return false; - - const size_t this_len = strlen(c_str()); - const size_t suffix_len = strlen(suffix); - return (this_len >= suffix_len) && - CStringEquals(c_str() + this_len - suffix_len, suffix); +// Formats an int value as "%02d". +std::string String::FormatIntWidth2(int value) { + std::stringstream ss; + ss << std::setfill('0') << std::setw(2) << value; + return ss.str(); } -// Returns true iff this String ends with the given suffix, ignoring case. -// Any String is considered to end with a NULL or empty suffix. -bool String::EndsWithCaseInsensitive(const char* suffix) const { - if (suffix == NULL || CStringEquals(suffix, "")) return true; - - if (c_str() == NULL) return false; - - const size_t this_len = strlen(c_str()); - const size_t suffix_len = strlen(suffix); - return (this_len >= suffix_len) && - CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix); +// Formats an int value as "%X". +std::string String::FormatHexInt(int value) { + std::stringstream ss; + ss << std::hex << std::uppercase << value; + return ss.str(); } -// Formats a list of arguments to a String, using the same format -// spec string as for printf. -// -// We do not use the StringPrintf class as it is not universally -// available. -// -// The result is limited to 4096 characters (including the tailing 0). -// If 4096 characters are not enough to format the input, or if -// there's an error, "<formatting error or buffer exceeded>" is -// returned. -String String::Format(const char * format, ...) { - va_list args; - va_start(args, format); - - char buffer[4096]; - const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]); - - // MSVC 8 deprecates vsnprintf(), so we want to suppress warning - // 4996 (deprecated function) there. -#ifdef _MSC_VER // We are using MSVC. -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4996) // Temporarily disables warning 4996. - - const int size = vsnprintf(buffer, kBufferSize, format, args); - -# pragma warning(pop) // Restores the warning state. -#else // We are not using MSVC. - const int size = vsnprintf(buffer, kBufferSize, format, args); -#endif // _MSC_VER - va_end(args); - - // vsnprintf()'s behavior is not portable. When the buffer is not - // big enough, it returns a negative value in MSVC, and returns the - // needed buffer size on Linux. When there is an output error, it - // always returns a negative value. For simplicity, we lump the two - // error cases together. - if (size < 0 || size >= kBufferSize) { - return String("<formatting error or buffer exceeded>"); - } else { - return String(buffer, size); - } +// Formats a byte as "%02X". +std::string String::FormatByte(unsigned char value) { + std::stringstream ss; + ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase + << static_cast<unsigned int>(value); + return ss.str(); } -// Converts the buffer in a stringstream to a String, converting NUL +// Converts the buffer in a stringstream to an std::string, converting NUL // bytes to "\\0" along the way. -String StringStreamToString(::std::stringstream* ss) { +std::string StringStreamToString(::std::stringstream* ss) { const ::std::string& str = ss->str(); const char* const start = str.c_str(); const char* const end = start + str.length(); - // We need to use a helper stringstream to do this transformation - // because String doesn't support push_back(). - ::std::stringstream helper; + std::string result; + result.reserve(2 * (end - start)); for (const char* ch = start; ch != end; ++ch) { if (*ch == '\0') { - helper << "\\0"; // Replaces NUL with "\\0"; + result += "\\0"; // Replaces NUL with "\\0"; } else { - helper.put(*ch); + result += *ch; } } - return String(helper.str().c_str()); + return result; } // Appends the user-supplied message to the Google-Test-generated message. -String AppendUserMessage(const String& gtest_msg, - const Message& user_msg) { +std::string AppendUserMessage(const std::string& gtest_msg, + const Message& user_msg) { // Appends the user message if it's non-empty. - const String user_msg_string = user_msg.GetString(); + const std::string user_msg_string = user_msg.GetString(); if (user_msg_string.empty()) { return gtest_msg; } - Message msg; - msg << gtest_msg << "\n" << user_msg_string; - - return msg.GetString(); + return gtest_msg + "\n" + user_msg_string; } } // namespace internal @@ -1811,8 +2054,9 @@ void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { // Adds a test property to the list. If a property with the same key as the // supplied property is already represented, the value of this test_property // replaces the old value for that key. -void TestResult::RecordProperty(const TestProperty& test_property) { - if (!ValidateTestProperty(test_property)) { +void TestResult::RecordProperty(const std::string& xml_element, + const TestProperty& test_property) { + if (!ValidateTestProperty(xml_element, test_property)) { return; } internal::MutexLock lock(&test_properites_mutex_); @@ -1826,21 +2070,94 @@ void TestResult::RecordProperty(const TestProperty& test_property) { property_with_matching_key->SetValue(test_property.value()); } -// Adds a failure if the key is a reserved attribute of Google Test -// testcase tags. Returns true if the property is valid. -bool TestResult::ValidateTestProperty(const TestProperty& test_property) { - internal::String key(test_property.key()); - if (key == "name" || key == "status" || key == "time" || key == "classname") { - ADD_FAILURE() - << "Reserved key used in RecordProperty(): " - << key - << " ('name', 'status', 'time', and 'classname' are reserved by " - << GTEST_NAME_ << ")"; +// The list of reserved attributes used in the <testsuites> element of XML +// output. +static const char* const kReservedTestSuitesAttributes[] = { + "disabled", + "errors", + "failures", + "name", + "random_seed", + "tests", + "time", + "timestamp" +}; + +// The list of reserved attributes used in the <testsuite> element of XML +// output. +static const char* const kReservedTestSuiteAttributes[] = { + "disabled", + "errors", + "failures", + "name", + "tests", + "time" +}; + +// The list of reserved attributes used in the <testcase> element of XML output. +static const char* const kReservedTestCaseAttributes[] = { + "classname", + "name", + "status", + "time", + "type_param", + "value_param" +}; + +template <int kSize> +std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) { + return std::vector<std::string>(array, array + kSize); +} + +static std::vector<std::string> GetReservedAttributesForElement( + const std::string& xml_element) { + if (xml_element == "testsuites") { + return ArrayAsVector(kReservedTestSuitesAttributes); + } else if (xml_element == "testsuite") { + return ArrayAsVector(kReservedTestSuiteAttributes); + } else if (xml_element == "testcase") { + return ArrayAsVector(kReservedTestCaseAttributes); + } else { + GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; + } + // This code is unreachable but some compilers may not realizes that. + return std::vector<std::string>(); +} + +static std::string FormatWordList(const std::vector<std::string>& words) { + Message word_list; + for (size_t i = 0; i < words.size(); ++i) { + if (i > 0 && words.size() > 2) { + word_list << ", "; + } + if (i == words.size() - 1) { + word_list << "and "; + } + word_list << "'" << words[i] << "'"; + } + return word_list.GetString(); +} + +bool ValidateTestPropertyName(const std::string& property_name, + const std::vector<std::string>& reserved_names) { + if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != + reserved_names.end()) { + ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name + << " (" << FormatWordList(reserved_names) + << " are reserved by " << GTEST_NAME_ << ")"; return false; } return true; } +// Adds a failure if the key is a reserved attribute of the element named +// xml_element. Returns true if the property is valid. +bool TestResult::ValidateTestProperty(const std::string& xml_element, + const TestProperty& test_property) { + return ValidateTestPropertyName(test_property.key(), + GetReservedAttributesForElement(xml_element)); +} + // Clears the object. void TestResult::Clear() { test_part_results_.clear(); @@ -1893,14 +2210,15 @@ int TestResult::test_property_count() const { // Creates a Test object. -// The c'tor saves the values of all Google Test flags. +// The c'tor saves the states of all flags. Test::Test() - : gtest_flag_saver_(new internal::GTestFlagSaver) { + : gtest_flag_saver_(new GTEST_FLAG_SAVER_) { } -// The d'tor restores the values of all Google Test flags. +// The d'tor restores the states of all flags. The actual work is +// done by the d'tor of the gtest_flag_saver_ field, and thus not +// visible here. Test::~Test() { - delete gtest_flag_saver_; } // Sets up the test fixture. @@ -1916,12 +2234,12 @@ void Test::TearDown() { } // Allows user supplied key value pairs to be recorded for later output. -void Test::RecordProperty(const char* key, const char* value) { - UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value); +void Test::RecordProperty(const std::string& key, const std::string& value) { + UnitTest::GetInstance()->RecordProperty(key, value); } // Allows user supplied key value pairs to be recorded for later output. -void Test::RecordProperty(const char* key, int value) { +void Test::RecordProperty(const std::string& key, int value) { Message value_message; value_message << value; RecordProperty(key, value_message.GetString().c_str()); @@ -1930,7 +2248,7 @@ void Test::RecordProperty(const char* key, int value) { namespace internal { void ReportFailureInUnknownLocation(TestPartResult::Type result_type, - const String& message) { + const std::string& message) { // This function is a friend of UnitTest and as such has access to // AddTestPartResult. UnitTest::GetInstance()->AddTestPartResult( @@ -1938,7 +2256,7 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type, NULL, // No info about the source file where the exception occurred. -1, // We have no info on which line caused the exception. message, - String()); // No stack trace, either. + ""); // No stack trace, either. } } // namespace internal @@ -1969,8 +2287,8 @@ bool Test::HasSameFixtureClass() { const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); if (first_is_TEST || this_is_TEST) { - // The user mixed TEST and TEST_F in this test case - we'll tell - // him/her how to fix it. + // Both TEST and TEST_F appear in same test case, which is incorrect. + // Tell the user how to fix this. // Gets the name of the TEST and the name of the TEST_F. Note // that first_is_TEST and this_is_TEST cannot both be true, as @@ -1990,8 +2308,8 @@ bool Test::HasSameFixtureClass() { << "want to change the TEST to TEST_F or move it to another test\n" << "case."; } else { - // The user defined two fixture classes with the same name in - // two namespaces - we'll tell him/her how to fix it. + // Two fixture classes with the same name appear in two different + // namespaces, which is not allowed. Tell the user how to fix this. ADD_FAILURE() << "All tests in the same test case must use the same test fixture\n" << "class. However, in test case " @@ -2015,22 +2333,24 @@ bool Test::HasSameFixtureClass() { // function returns its result via an output parameter pointer because VC++ // prohibits creation of objects with destructors on stack in functions // using __try (see error C2712). -static internal::String* FormatSehExceptionMessage(DWORD exception_code, - const char* location) { +static std::string* FormatSehExceptionMessage(DWORD exception_code, + const char* location) { Message message; message << "SEH exception with code 0x" << std::setbase(16) << exception_code << std::setbase(10) << " thrown in " << location << "."; - return new internal::String(message.GetString()); + return new std::string(message.GetString()); } #endif // GTEST_HAS_SEH +namespace internal { + #if GTEST_HAS_EXCEPTIONS // Adds an "exception thrown" fatal failure to the current test. -static internal::String FormatCxxExceptionMessage(const char* description, - const char* location) { +static std::string FormatCxxExceptionMessage(const char* description, + const char* location) { Message message; if (description != NULL) { message << "C++ exception with description \"" << description << "\""; @@ -2042,23 +2362,15 @@ static internal::String FormatCxxExceptionMessage(const char* description, return message.GetString(); } -static internal::String PrintTestPartResultToString( +static std::string PrintTestPartResultToString( const TestPartResult& test_part_result); -// A failed Google Test assertion will throw an exception of this type when -// GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We -// derive it from std::runtime_error, which is for errors presumably -// detectable only at run time. Since std::runtime_error inherits from -// std::exception, many testing frameworks know how to extract and print the -// message inside it. -class GoogleTestFailureException : public ::std::runtime_error { - public: - explicit GoogleTestFailureException(const TestPartResult& failure) - : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} -}; +GoogleTestFailureException::GoogleTestFailureException( + const TestPartResult& failure) + : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} + #endif // GTEST_HAS_EXCEPTIONS -namespace internal { // We put these helper functions in the internal namespace as IBM's xlC // compiler rejects the code if they were declared static. @@ -2078,7 +2390,7 @@ Result HandleSehExceptionsInMethodIfSupported( // We create the exception message on the heap because VC++ prohibits // creation of objects with destructors on stack in functions using __try // (see error C2712). - internal::String* exception_message = FormatSehExceptionMessage( + std::string* exception_message = FormatSehExceptionMessage( GetExceptionCode(), location); internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, *exception_message); @@ -2124,9 +2436,10 @@ Result HandleExceptionsInMethodIfSupported( #if GTEST_HAS_EXCEPTIONS try { return HandleSehExceptionsInMethodIfSupported(object, method, location); - } catch (const GoogleTestFailureException&) { // NOLINT - // This exception doesn't originate in code under test. It makes no - // sense to report it as a test failure. + } catch (const internal::GoogleTestFailureException&) { // NOLINT + // This exception type can only be thrown by a failed Google + // Test assertion with the intention of letting another testing + // framework catch it. Therefore we just re-throw it. throw; } catch (const std::exception& e) { // NOLINT internal::ReportFailureInUnknownLocation( @@ -2185,18 +2498,18 @@ bool Test::HasNonfatalFailure() { // Constructs a TestInfo object. It assumes ownership of the test factory // object. -// TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s -// to signify they cannot be NULLs. -TestInfo::TestInfo(const char* a_test_case_name, - const char* a_name, +TestInfo::TestInfo(const std::string& a_test_case_name, + const std::string& a_name, const char* a_type_param, const char* a_value_param, + internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) : test_case_name_(a_test_case_name), name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : NULL), value_param_(a_value_param ? new std::string(a_value_param) : NULL), + location_(a_code_location), fixture_class_id_(fixture_class_id), should_run_(false), is_disabled_(false), @@ -2220,6 +2533,7 @@ namespace internal { // this is not a typed or a type-parameterized test. // value_param: text representation of the test's value parameter, // or NULL if this is not a value-parameterized test. +// code_location: code location where the test is defined // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case @@ -2227,23 +2541,25 @@ namespace internal { // The newly created TestInfo instance will assume // ownership of the factory object. TestInfo* MakeAndRegisterTestInfo( - const char* test_case_name, const char* name, + const char* test_case_name, + const char* name, const char* type_param, const char* value_param, + CodeLocation code_location, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase* factory) { TestInfo* const test_info = new TestInfo(test_case_name, name, type_param, value_param, - fixture_class_id, factory); + code_location, fixture_class_id, factory); GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); return test_info; } #if GTEST_HAS_PARAM_TEST void ReportInvalidTestCaseType(const char* test_case_name, - const char* file, int line) { + CodeLocation code_location) { Message errors; errors << "Attempted redefinition of test case " << test_case_name << ".\n" @@ -2255,13 +2571,44 @@ void ReportInvalidTestCaseType(const char* test_case_name, << "probably rename one of the classes to put the tests into different\n" << "test cases."; - fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), + fprintf(stderr, "%s %s", + FormatFileLocation(code_location.file.c_str(), + code_location.line).c_str(), errors.GetString().c_str()); } #endif // GTEST_HAS_PARAM_TEST } // namespace internal +namespace { + +// A predicate that checks the test name of a TestInfo against a known +// value. +// +// This is used for implementation of the TestCase class only. We put +// it in the anonymous namespace to prevent polluting the outer +// namespace. +// +// TestNameIs is copyable. +class TestNameIs { + public: + // Constructor. + // + // TestNameIs has NO default constructor. + explicit TestNameIs(const char* name) + : name_(name) {} + + // Returns true iff the test name of test_info matches name_. + bool operator()(const TestInfo * test_info) const { + return test_info && test_info->name() == name_; + } + + private: + std::string name_; +}; + +} // namespace + namespace internal { // This method expands all parameterized tests registered with macros TEST_P @@ -2336,10 +2683,21 @@ int TestCase::failed_test_count() const { return CountIf(test_info_list_, TestFailed); } +// Gets the number of disabled tests that will be reported in the XML report. +int TestCase::reportable_disabled_test_count() const { + return CountIf(test_info_list_, TestReportableDisabled); +} + +// Gets the number of disabled tests in this test case. int TestCase::disabled_test_count() const { return CountIf(test_info_list_, TestDisabled); } +// Gets the number of tests to be printed in the XML report. +int TestCase::reportable_test_count() const { + return CountIf(test_info_list_, TestReportable); +} + // Get the number of tests in this test case that should run. int TestCase::test_to_run_count() const { return CountIf(test_info_list_, ShouldRunTest); @@ -2427,6 +2785,7 @@ void TestCase::Run() { // Clears the results of all tests in this test case. void TestCase::ClearResult() { + ad_hoc_test_result_.Clear(); ForEach(test_info_list_, TestInfo::ClearTestResult); } @@ -2447,20 +2806,20 @@ void TestCase::UnshuffleTests() { // // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(5, "book", "books") returns "5 books". -static internal::String FormatCountableNoun(int count, - const char * singular_form, - const char * plural_form) { - return internal::String::Format("%d %s", count, - count == 1 ? singular_form : plural_form); +static std::string FormatCountableNoun(int count, + const char * singular_form, + const char * plural_form) { + return internal::StreamableToString(count) + " " + + (count == 1 ? singular_form : plural_form); } // Formats the count of tests. -static internal::String FormatTestCount(int test_count) { +static std::string FormatTestCount(int test_count) { return FormatCountableNoun(test_count, "test", "tests"); } // Formats the count of test cases. -static internal::String FormatTestCaseCount(int test_case_count) { +static std::string FormatTestCaseCount(int test_case_count) { return FormatCountableNoun(test_case_count, "test case", "test cases"); } @@ -2480,14 +2839,15 @@ static const char * TestPartResultTypeToString(TestPartResult::Type type) { #else return "Failure\n"; #endif + default: + return "Unknown result type"; } - - // All cases return, so this is unreachable but GCC doesn't know it - abort(); } -// Prints a TestPartResult to a String. -static internal::String PrintTestPartResultToString( +namespace internal { + +// Prints a TestPartResult to an std::string. +static std::string PrintTestPartResultToString( const TestPartResult& test_part_result) { return (Message() << internal::FormatFileLocation(test_part_result.file_name(), @@ -2498,7 +2858,7 @@ static internal::String PrintTestPartResultToString( // Prints a TestPartResult. static void PrintTestPartResult(const TestPartResult& test_part_result) { - const internal::String& result = + const std::string& result = PrintTestPartResultToString(test_part_result); printf("%s\n", result.c_str()); fflush(stdout); @@ -2517,8 +2877,6 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) { // class PrettyUnitTestResultPrinter -namespace internal { - enum GTestColor { COLOR_DEFAULT, COLOR_RED, @@ -2526,7 +2884,8 @@ enum GTestColor { COLOR_YELLOW }; -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ + !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Returns the character attribute for the given color. WORD GetColorAttribute(GTestColor color) { @@ -2570,6 +2929,11 @@ bool ShouldUseColor(bool stdout_is_tty) { String::CStringEquals(term, "xterm-color") || String::CStringEquals(term, "xterm-256color") || String::CStringEquals(term, "screen") || + String::CStringEquals(term, "screen-256color") || + String::CStringEquals(term, "tmux") || + String::CStringEquals(term, "tmux-256color") || + String::CStringEquals(term, "rxvt-unicode") || + String::CStringEquals(term, "rxvt-unicode-256color") || String::CStringEquals(term, "linux") || String::CStringEquals(term, "cygwin"); return stdout_is_tty && term_supports_color; @@ -2593,8 +2957,9 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS - const bool use_color = false; +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \ + GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT + const bool use_color = AlwaysFalse(); #else static const bool in_color_mode = ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); @@ -2608,7 +2973,8 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) { return; } -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ + !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); // Gets the current text color. @@ -2635,6 +3001,11 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_end(args); } +// Text printed in Google Test's text output and --gunit_list_tests +// output to label the type parameter and value parameter for a test. +static const char kTypeParamLabel[] = "TypeParam"; +static const char kValueParamLabel[] = "GetParam()"; + void PrintFullTestCommentIfPresent(const TestInfo& test_info) { const char* const type_param = test_info.type_param(); const char* const value_param = test_info.value_param(); @@ -2642,12 +3013,12 @@ void PrintFullTestCommentIfPresent(const TestInfo& test_info) { if (type_param != NULL || value_param != NULL) { printf(", where "); if (type_param != NULL) { - printf("TypeParam = %s", type_param); + printf("%s = %s", kTypeParamLabel, type_param); if (value_param != NULL) printf(" and "); } if (value_param != NULL) { - printf("GetParam() = %s", value_param); + printf("%s = %s", kValueParamLabel, value_param); } } } @@ -2663,24 +3034,22 @@ class PrettyUnitTestResultPrinter : public TestEventListener { } // The following methods override what's in the TestEventListener class. - void OnTestProgramStart(const UnitTest & /*unit_test*/) override {} - void OnTestIterationStart(const UnitTest &unit_test, int iteration) override; - void OnEnvironmentsSetUpStart(const UnitTest &unit_test) override; - void OnEnvironmentsSetUpEnd(const UnitTest & /*unit_test*/) override {} - void OnTestCaseStart(const TestCase &test_case) override; - void OnTestStart(const TestInfo &test_info) override; - void OnTestPartResult(const TestPartResult &result) override; - void OnTestEnd(const TestInfo &test_info) override; - void OnTestCaseEnd(const TestCase &test_case) override; - void OnEnvironmentsTearDownStart(const UnitTest &unit_test) override; - void OnEnvironmentsTearDownEnd(const UnitTest & /*unit_test*/) override {} - void OnTestIterationEnd(const UnitTest &unit_test, int iteration) override; - void OnTestProgramEnd(const UnitTest & /*unit_test*/) override {} + virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); + virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestCaseStart(const TestCase& test_case); + virtual void OnTestStart(const TestInfo& test_info); + virtual void OnTestPartResult(const TestPartResult& result); + virtual void OnTestEnd(const TestInfo& test_info); + virtual void OnTestCaseEnd(const TestCase& test_case); + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); + virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} private: static void PrintFailedTests(const UnitTest& unit_test); - - internal::String test_case_name_; }; // Fired before each iteration of tests starts. @@ -2693,7 +3062,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart( // Prints the filter if it's not *. This reminds the user that some // tests may be skipped. - if (!internal::String::CStringEquals(filter, kUniversalFilter)) { + if (!String::CStringEquals(filter, kUniversalFilter)) { ColoredPrintf(COLOR_YELLOW, "Note: %s filter = %s\n", GTEST_NAME_, filter); } @@ -2727,22 +3096,21 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( } void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { - test_case_name_ = test_case.name(); - const internal::String counts = + const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("%s from %s", counts.c_str(), test_case_name_.c_str()); + printf("%s from %s", counts.c_str(), test_case.name()); if (test_case.type_param() == NULL) { printf("\n"); } else { - printf(", where TypeParam = %s\n", test_case.type_param()); + printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); } fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { ColoredPrintf(COLOR_GREEN, "[ RUN ] "); - PrintTestName(test_case_name_.c_str(), test_info.name()); + PrintTestName(test_info.test_case_name(), test_info.name()); printf("\n"); fflush(stdout); } @@ -2765,7 +3133,7 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { } else { ColoredPrintf(COLOR_RED, "[ FAILED ] "); } - PrintTestName(test_case_name_.c_str(), test_info.name()); + PrintTestName(test_info.test_case_name(), test_info.name()); if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); @@ -2781,12 +3149,11 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { if (!GTEST_FLAG(print_time)) return; - test_case_name_ = test_case.name(); - const internal::String counts = + const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); printf("%s from %s (%s ms total)\n\n", - counts.c_str(), test_case_name_.c_str(), + counts.c_str(), test_case.name(), internal::StreamableToString(test_case.elapsed_time()).c_str()); fflush(stdout); } @@ -2847,7 +3214,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, num_failures == 1 ? "TEST" : "TESTS"); } - int num_disabled = unit_test.disabled_test_count(); + int num_disabled = unit_test.reportable_disabled_test_count(); if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { if (!num_failures) { printf("\n"); // Add a spacer if no FAILURE banner is displayed. @@ -2869,7 +3236,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, class TestEventRepeater : public TestEventListener { public: TestEventRepeater() : forwarding_enabled_(true) {} - ~TestEventRepeater() override; + virtual ~TestEventRepeater(); void Append(TestEventListener *listener); TestEventListener* Release(TestEventListener* listener); @@ -2878,19 +3245,19 @@ class TestEventRepeater : public TestEventListener { bool forwarding_enabled() const { return forwarding_enabled_; } void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } - void OnTestProgramStart(const UnitTest &unit_test) override; - void OnTestIterationStart(const UnitTest &unit_test, int iteration) override; - void OnEnvironmentsSetUpStart(const UnitTest &unit_test) override; - void OnEnvironmentsSetUpEnd(const UnitTest &unit_test) override; - void OnTestCaseStart(const TestCase &test_case) override; - void OnTestStart(const TestInfo &test_info) override; - void OnTestPartResult(const TestPartResult &result) override; - void OnTestEnd(const TestInfo &test_info) override; - void OnTestCaseEnd(const TestCase &test_case) override; - void OnEnvironmentsTearDownStart(const UnitTest &unit_test) override; - void OnEnvironmentsTearDownEnd(const UnitTest &unit_test) override; - void OnTestIterationEnd(const UnitTest &unit_test, int iteration) override; - void OnTestProgramEnd(const UnitTest &unit_test) override; + virtual void OnTestProgramStart(const UnitTest& unit_test); + virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); + virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); + virtual void OnTestCaseStart(const TestCase& test_case); + virtual void OnTestStart(const TestInfo& test_info); + virtual void OnTestPartResult(const TestPartResult& result); + virtual void OnTestEnd(const TestInfo& test_info); + virtual void OnTestCaseEnd(const TestCase& test_case); + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); + virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + virtual void OnTestProgramEnd(const UnitTest& unit_test); private: // Controls whether events will be forwarded to listeners_. Set to false @@ -2983,7 +3350,7 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener { public: explicit XmlUnitTestResultPrinter(const char* output_file); - void OnTestIterationEnd(const UnitTest &unit_test, int iteration) override; + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); private: // Is c a whitespace character that is normalized to a space character @@ -3001,18 +3368,27 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener { // is_attribute is true, the text is meant to appear as an attribute // value, and normalizable whitespace is preserved by replacing it // with character references. - static String EscapeXml(const char* str, bool is_attribute); + static std::string EscapeXml(const std::string& str, bool is_attribute); // Returns the given string with all characters invalid in XML removed. - static string RemoveInvalidXmlCharacters(const string& str); + static std::string RemoveInvalidXmlCharacters(const std::string& str); // Convenience wrapper around EscapeXml when str is an attribute value. - static String EscapeXmlAttribute(const char* str) { + static std::string EscapeXmlAttribute(const std::string& str) { return EscapeXml(str, true); } // Convenience wrapper around EscapeXml when str is not an attribute value. - static String EscapeXmlText(const char* str) { return EscapeXml(str, false); } + static std::string EscapeXmlText(const char* str) { + return EscapeXml(str, false); + } + + // Verifies that the given attribute belongs to the given element and + // streams the attribute as XML. + static void OutputXmlAttribute(std::ostream* stream, + const std::string& element_name, + const std::string& name, + const std::string& value); // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. static void OutputXmlCDataSection(::std::ostream* stream, const char* data); @@ -3023,19 +3399,21 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener { const TestInfo& test_info); // Prints an XML representation of a TestCase object - static void PrintXmlTestCase(FILE* out, const TestCase& test_case); + static void PrintXmlTestCase(::std::ostream* stream, + const TestCase& test_case); // Prints an XML summary of unit_test to output stream out. - static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test); + static void PrintXmlUnitTest(::std::ostream* stream, + const UnitTest& unit_test); // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. - // When the String is not empty, it includes a space at the beginning, + // When the std::string is not empty, it includes a space at the beginning, // to delimit this attribute from prior attributes. - static String TestPropertiesAsXmlAttributes(const TestResult& result); + static std::string TestPropertiesAsXmlAttributes(const TestResult& result); // The output file. - const String output_file_; + const std::string output_file_; GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); }; @@ -3077,7 +3455,9 @@ void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, fflush(stderr); exit(EXIT_FAILURE); } - PrintXmlUnitTest(xmlout, unit_test); + std::stringstream stream; + PrintXmlUnitTest(&stream, unit_test); + fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); fclose(xmlout); } @@ -3093,42 +3473,43 @@ void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, // most invalid characters can be retained using character references. // TODO(wan): It might be nice to have a minimally invasive, human-readable // escaping scheme for invalid characters, rather than dropping them. -String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) { +std::string XmlUnitTestResultPrinter::EscapeXml( + const std::string& str, bool is_attribute) { Message m; - if (str != NULL) { - for (const char* src = str; *src; ++src) { - switch (*src) { - case '<': - m << "<"; - break; - case '>': - m << ">"; - break; - case '&': - m << "&"; - break; - case '\'': - if (is_attribute) - m << "'"; - else - m << '\''; - break; - case '"': - if (is_attribute) - m << """; + for (size_t i = 0; i < str.size(); ++i) { + const char ch = str[i]; + switch (ch) { + case '<': + m << "<"; + break; + case '>': + m << ">"; + break; + case '&': + m << "&"; + break; + case '\'': + if (is_attribute) + m << "'"; + else + m << '\''; + break; + case '"': + if (is_attribute) + m << """; + else + m << '"'; + break; + default: + if (IsValidXmlCharacter(ch)) { + if (is_attribute && IsNormalizableWhitespace(ch)) + m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch)) + << ";"; else - m << '"'; - break; - default: - if (IsValidXmlCharacter(*src)) { - if (is_attribute && IsNormalizableWhitespace(*src)) - m << String::Format("&#x%02X;", unsigned(*src)); - else - m << *src; - } - break; - } + m << ch; + } + break; } } @@ -3138,10 +3519,11 @@ String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) { // Returns the given string with all characters invalid in XML removed. // Currently invalid characters are dropped from the string. An // alternative is to replace them with certain characters such as . or ?. -string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) { - string output; +std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( + const std::string& str) { + std::string output; output.reserve(str.size()); - for (string::const_iterator it = str.begin(); it != str.end(); ++it) + for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) if (IsValidXmlCharacter(*it)) output.push_back(*it); @@ -3167,10 +3549,41 @@ string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) { // Formats the given time in milliseconds as seconds. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { ::std::stringstream ss; - ss << ms/1000.0; + ss << (static_cast<double>(ms) * 1e-3); return ss.str(); } +static bool PortableLocaltime(time_t seconds, struct tm* out) { +#if defined(_MSC_VER) + return localtime_s(out, &seconds) == 0; +#elif defined(__MINGW32__) || defined(__MINGW64__) + // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses + // Windows' localtime(), which has a thread-local tm buffer. + struct tm* tm_ptr = localtime(&seconds); // NOLINT + if (tm_ptr == NULL) + return false; + *out = *tm_ptr; + return true; +#else + return localtime_r(&seconds, out) != NULL; +#endif +} + +// Converts the given epoch time in milliseconds to a date string in the ISO +// 8601 format, without the timezone information. +std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { + struct tm time_struct; + if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct)) + return ""; + // YYYY-MM-DDThh:mm:ss + return StreamableToString(time_struct.tm_year + 1900) + "-" + + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + + String::FormatIntWidth2(time_struct.tm_mday) + "T" + + String::FormatIntWidth2(time_struct.tm_hour) + ":" + + String::FormatIntWidth2(time_struct.tm_min) + ":" + + String::FormatIntWidth2(time_struct.tm_sec); +} + // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, const char* data) { @@ -3191,45 +3604,63 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, *stream << "]]>"; } +void XmlUnitTestResultPrinter::OutputXmlAttribute( + std::ostream* stream, + const std::string& element_name, + const std::string& name, + const std::string& value) { + const std::vector<std::string>& allowed_names = + GetReservedAttributesForElement(element_name); + + GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != + allowed_names.end()) + << "Attribute " << name << " is not allowed for element <" << element_name + << ">."; + + *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; +} + // Prints an XML representation of a TestInfo object. // TODO(wan): There is also value in printing properties with the plain printer. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); - *stream << " <testcase name=\"" - << EscapeXmlAttribute(test_info.name()).c_str() << "\""; + const std::string kTestcase = "testcase"; + + *stream << " <testcase"; + OutputXmlAttribute(stream, kTestcase, "name", test_info.name()); if (test_info.value_param() != NULL) { - *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param()) - << "\""; + OutputXmlAttribute(stream, kTestcase, "value_param", + test_info.value_param()); } if (test_info.type_param() != NULL) { - *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param()) - << "\""; + OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param()); } - *stream << " status=\"" - << (test_info.should_run() ? "run" : "notrun") - << "\" time=\"" - << FormatTimeInMillisAsSeconds(result.elapsed_time()) - << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str() - << "\"" << TestPropertiesAsXmlAttributes(result).c_str(); + OutputXmlAttribute(stream, kTestcase, "status", + test_info.should_run() ? "run" : "notrun"); + OutputXmlAttribute(stream, kTestcase, "time", + FormatTimeInMillisAsSeconds(result.elapsed_time())); + OutputXmlAttribute(stream, kTestcase, "classname", test_case_name); + *stream << TestPropertiesAsXmlAttributes(result); int failures = 0; for (int i = 0; i < result.total_part_count(); ++i) { const TestPartResult& part = result.GetTestPartResult(i); if (part.failed()) { - if (++failures == 1) + if (++failures == 1) { *stream << ">\n"; - *stream << " <failure message=\"" - << EscapeXmlAttribute(part.summary()).c_str() - << "\" type=\"\">"; + } const string location = internal::FormatCompilerIndependentFileLocation( part.file_name(), part.line_number()); - const string message = location + "\n" + part.message(); - OutputXmlCDataSection(stream, - RemoveInvalidXmlCharacters(message).c_str()); + const string summary = location + "\n" + part.summary(); + *stream << " <failure message=\"" + << EscapeXmlAttribute(summary.c_str()) + << "\" type=\"\">"; + const string detail = location + "\n" + part.message(); + OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); *stream << "</failure>\n"; } } @@ -3241,49 +3672,73 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, } // Prints an XML representation of a TestCase object -void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out, +void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, const TestCase& test_case) { - fprintf(out, - " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" " - "disabled=\"%d\" ", - EscapeXmlAttribute(test_case.name()).c_str(), - test_case.total_test_count(), - test_case.failed_test_count(), - test_case.disabled_test_count()); - fprintf(out, - "errors=\"0\" time=\"%s\">\n", - FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str()); + const std::string kTestsuite = "testsuite"; + *stream << " <" << kTestsuite; + OutputXmlAttribute(stream, kTestsuite, "name", test_case.name()); + OutputXmlAttribute(stream, kTestsuite, "tests", + StreamableToString(test_case.reportable_test_count())); + OutputXmlAttribute(stream, kTestsuite, "failures", + StreamableToString(test_case.failed_test_count())); + OutputXmlAttribute( + stream, kTestsuite, "disabled", + StreamableToString(test_case.reportable_disabled_test_count())); + OutputXmlAttribute(stream, kTestsuite, "errors", "0"); + OutputXmlAttribute(stream, kTestsuite, "time", + FormatTimeInMillisAsSeconds(test_case.elapsed_time())); + *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result()) + << ">\n"; + for (int i = 0; i < test_case.total_test_count(); ++i) { - ::std::stringstream stream; - OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i)); - fprintf(out, "%s", StringStreamToString(&stream).c_str()); + if (test_case.GetTestInfo(i)->is_reportable()) + OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i)); } - fprintf(out, " </testsuite>\n"); + *stream << " </" << kTestsuite << ">\n"; } // Prints an XML summary of unit_test to output stream out. -void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out, +void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, const UnitTest& unit_test) { - fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); - fprintf(out, - "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" " - "errors=\"0\" time=\"%s\" ", - unit_test.total_test_count(), - unit_test.failed_test_count(), - unit_test.disabled_test_count(), - FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str()); + const std::string kTestsuites = "testsuites"; + + *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; + *stream << "<" << kTestsuites; + + OutputXmlAttribute(stream, kTestsuites, "tests", + StreamableToString(unit_test.reportable_test_count())); + OutputXmlAttribute(stream, kTestsuites, "failures", + StreamableToString(unit_test.failed_test_count())); + OutputXmlAttribute( + stream, kTestsuites, "disabled", + StreamableToString(unit_test.reportable_disabled_test_count())); + OutputXmlAttribute(stream, kTestsuites, "errors", "0"); + OutputXmlAttribute( + stream, kTestsuites, "timestamp", + FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); + OutputXmlAttribute(stream, kTestsuites, "time", + FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); + if (GTEST_FLAG(shuffle)) { - fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed()); + OutputXmlAttribute(stream, kTestsuites, "random_seed", + StreamableToString(unit_test.random_seed())); + } + + *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); + + OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); + *stream << ">\n"; + + for (int i = 0; i < unit_test.total_test_case_count(); ++i) { + if (unit_test.GetTestCase(i)->reportable_test_count() > 0) + PrintXmlTestCase(stream, *unit_test.GetTestCase(i)); } - fprintf(out, "name=\"AllTests\">\n"); - for (int i = 0; i < unit_test.total_test_case_count(); ++i) - PrintXmlTestCase(out, *unit_test.GetTestCase(i)); - fprintf(out, "</testsuites>\n"); + *stream << "</" << kTestsuites << ">\n"; } // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. -String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( +std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( const TestResult& result) { Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { @@ -3298,114 +3753,6 @@ String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( #if GTEST_CAN_STREAM_RESULTS_ -// Streams test results to the given port on the given host machine. -class StreamingListener : public EmptyTestEventListener { - public: - // Escapes '=', '&', '%', and '\n' characters in str as "%xx". - static string UrlEncode(const char* str); - - StreamingListener(const string& host, const string& port) - : sockfd_(-1), host_name_(host), port_num_(port) { - MakeConnection(); - Send("gtest_streaming_protocol_version=1.0\n"); - } - - ~StreamingListener() override { - if (sockfd_ != -1) - CloseConnection(); - } - - void OnTestProgramStart(const UnitTest & /* unit_test */) override { - Send("event=TestProgramStart\n"); - } - - void OnTestProgramEnd(const UnitTest &unit_test) override { - // Note that Google Test current only report elapsed time for each - // test iteration, not for the entire test program. - Send(String::Format("event=TestProgramEnd&passed=%d\n", - unit_test.Passed())); - - // Notify the streaming server to stop. - CloseConnection(); - } - - void OnTestIterationStart(const UnitTest & /* unit_test */, - int iteration) override { - Send(String::Format("event=TestIterationStart&iteration=%d\n", - iteration)); - } - - void OnTestIterationEnd(const UnitTest &unit_test, - int /* iteration */) override { - Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n", - unit_test.Passed(), - StreamableToString(unit_test.elapsed_time()).c_str())); - } - - void OnTestCaseStart(const TestCase &test_case) override { - Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name())); - } - - void OnTestCaseEnd(const TestCase &test_case) override { - Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n", - test_case.Passed(), - StreamableToString(test_case.elapsed_time()).c_str())); - } - - void OnTestStart(const TestInfo &test_info) override { - Send(String::Format("event=TestStart&name=%s\n", test_info.name())); - } - - void OnTestEnd(const TestInfo &test_info) override { - Send(String::Format( - "event=TestEnd&passed=%d&elapsed_time=%sms\n", - (test_info.result())->Passed(), - StreamableToString((test_info.result())->elapsed_time()).c_str())); - } - - void OnTestPartResult(const TestPartResult &test_part_result) override { - const char* file_name = test_part_result.file_name(); - if (file_name == NULL) - file_name = ""; - Send(String::Format("event=TestPartResult&file=%s&line=%d&message=", - UrlEncode(file_name).c_str(), - test_part_result.line_number())); - Send(UrlEncode(test_part_result.message()) + "\n"); - } - - private: - // Creates a client socket and connects to the server. - void MakeConnection(); - - // Closes the socket. - void CloseConnection() { - GTEST_CHECK_(sockfd_ != -1) - << "CloseConnection() can be called only when there is a connection."; - - close(sockfd_); - sockfd_ = -1; - } - - // Sends a string to the socket. - void Send(const string& message) { - GTEST_CHECK_(sockfd_ != -1) - << "Send() can be called only when there is a connection."; - - const int len = static_cast<int>(message.length()); - if (write(sockfd_, message.c_str(), len) != len) { - GTEST_LOG_(WARNING) - << "stream_result_to: failed to stream to " - << host_name_ << ":" << port_num_; - } - } - - int sockfd_; // socket file descriptor - const string host_name_; - const string port_num_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); -}; // class StreamingListener - // Checks if str contains '=', '&', '%' or '\n' characters. If yes, // replaces them by "%xx" where xx is their hexadecimal value. For // example, replaces "=" with "%3D". This algorithm is O(strlen(str)) @@ -3420,7 +3767,7 @@ string StreamingListener::UrlEncode(const char* str) { case '=': case '&': case '\n': - result.append(String::Format("%%%02x", static_cast<unsigned char>(ch))); + result.append("%" + String::FormatByte(static_cast<unsigned char>(ch))); break; default: result.push_back(ch); @@ -3430,7 +3777,7 @@ string StreamingListener::UrlEncode(const char* str) { return result; } -void StreamingListener::MakeConnection() { +void StreamingListener::SocketWriter::MakeConnection() { GTEST_CHECK_(sockfd_ == -1) << "MakeConnection() can't be called when there is already a connection."; @@ -3478,8 +3825,8 @@ void StreamingListener::MakeConnection() { // Pushes the given source file location and message onto a per-thread // trace stack maintained by Google Test. -// L < UnitTest::mutex_ -ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) { +ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) + GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { TraceInfo trace; trace.file = file; trace.line = line; @@ -3489,34 +3836,52 @@ ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) { } // Pops the info pushed by the c'tor. -// L < UnitTest::mutex_ -ScopedTrace::~ScopedTrace() { +ScopedTrace::~ScopedTrace() + GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { UnitTest::GetInstance()->PopGTestTrace(); } // class OsStackTraceGetter -// Returns the current OS stack trace as a String. Parameters: -// -// max_depth - the maximum number of stack frames to be included -// in the trace. -// skip_count - the number of top frames to be skipped; doesn't count -// against max_depth. -// -// L < mutex_ -// We use "L < mutex_" to denote that the function may acquire mutex_. -String OsStackTraceGetter::CurrentStackTrace(int, int) { - return String(""); -} +const char* const OsStackTraceGetterInterface::kElidedFramesMarker = + "... " GTEST_NAME_ " internal frames ..."; -// L < mutex_ -void OsStackTraceGetter::UponLeavingGTest() { +string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/, + int /*skip_count*/) { + return ""; } -const char* const -OsStackTraceGetter::kElidedFramesMarker = - "... " GTEST_NAME_ " internal frames ..."; +void OsStackTraceGetter::UponLeavingGTest() {} + +// A helper class that creates the premature-exit file in its +// constructor and deletes the file in its destructor. +class ScopedPrematureExitFile { + public: + explicit ScopedPrematureExitFile(const char* premature_exit_filepath) + : premature_exit_filepath_(premature_exit_filepath) { + // If a path to the premature-exit file is specified... + if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') { + // create the file with a single "0" character in it. I/O + // errors are ignored as there's nothing better we can do and we + // don't want to fail the test because of this. + FILE* pfile = posix::FOpen(premature_exit_filepath, "w"); + fwrite("0", 1, 1, pfile); + fclose(pfile); + } + } + + ~ScopedPrematureExitFile() { + if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') { + remove(premature_exit_filepath_); + } + } + + private: + const char* const premature_exit_filepath_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); +}; } // namespace internal @@ -3604,7 +3969,7 @@ void TestEventListeners::SuppressEventForwarding() { // We don't protect this under mutex_ as a user is not supposed to // call this before main() starts, from which point on the return // value will never change. -UnitTest * UnitTest::GetInstance() { +UnitTest* UnitTest::GetInstance() { // When compiled with MSVC 7.1 in optimized mode, destroying the // UnitTest object upon exiting the program messes up the exit code, // causing successful tests to appear failed. We have to use a @@ -3654,17 +4019,33 @@ int UnitTest::successful_test_count() const { // Gets the number of failed tests. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } +// Gets the number of disabled tests that will be reported in the XML report. +int UnitTest::reportable_disabled_test_count() const { + return impl()->reportable_disabled_test_count(); +} + // Gets the number of disabled tests. int UnitTest::disabled_test_count() const { return impl()->disabled_test_count(); } +// Gets the number of tests to be printed in the XML report. +int UnitTest::reportable_test_count() const { + return impl()->reportable_test_count(); +} + // Gets the number of all tests. int UnitTest::total_test_count() const { return impl()->total_test_count(); } // Gets the number of tests that should run. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } +// Gets the time of the test program start, in ms from the start of the +// UNIX epoch. +internal::TimeInMillis UnitTest::start_timestamp() const { + return impl()->start_timestamp(); +} + // Gets the elapsed time, in milliseconds. internal::TimeInMillis UnitTest::elapsed_time() const { return impl()->elapsed_time(); @@ -3683,6 +4064,12 @@ const TestCase* UnitTest::GetTestCase(int i) const { return impl()->GetTestCase(i); } +// Returns the TestResult containing information on test failures and +// properties logged outside of individual test cases. +const TestResult& UnitTest::ad_hoc_test_result() const { + return *impl()->ad_hoc_test_result(); +} + // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* UnitTest::GetMutableTestCase(int i) { @@ -3718,12 +4105,12 @@ Environment* UnitTest::AddEnvironment(Environment* env) { // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // this to report their results. The user code should use the // assertion macros instead of calling this directly. -// L < mutex_ -void UnitTest::AddTestPartResult(TestPartResult::Type result_type, - const char* file_name, - int line_number, - const internal::String& message, - const internal::String& os_stack_trace) { +void UnitTest::AddTestPartResult( + TestPartResult::Type result_type, + const char* file_name, + int line_number, + const std::string& message, + const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { Message msg; msg << message; @@ -3756,17 +4143,21 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type, // with another testing framework) and specify the former on the // command line for debugging. if (GTEST_FLAG(break_on_failure)) { -#if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Using DebugBreak on Windows allows gtest to still break into a debugger // when a failure happens and both the --gtest_break_on_failure and // the --gtest_catch_exceptions flags are specified. DebugBreak(); #else - abort(); + // Dereference NULL through a volatile pointer to prevent the compiler + // from removing. We use this rather than abort() or __builtin_trap() for + // portability: Symbian doesn't implement abort() well, and some debuggers + // don't correctly trap abort(). + *static_cast<volatile int*>(NULL) = 1; #endif // GTEST_OS_WINDOWS } else if (GTEST_FLAG(throw_on_failure)) { #if GTEST_HAS_EXCEPTIONS - throw GoogleTestFailureException(result); + throw internal::GoogleTestFailureException(result); #else // We cannot call abort() as it generates a pop-up in debug mode // that cannot be suppressed in VC 7.1 or below. @@ -3776,12 +4167,14 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type, } } -// Creates and adds a property to the current TestResult. If a property matching -// the supplied value already exists, updates its value instead. -void UnitTest::RecordPropertyForCurrentTest(const char* key, - const char* value) { - const TestProperty test_property(key, value); - impl_->current_test_result()->RecordProperty(test_property); +// Adds a TestProperty to the current TestResult object when invoked from +// inside a test, to current TestCase's ad_hoc_test_result_ when invoked +// from SetUpTestCase or TearDownTestCase, or to the global property set +// when invoked elsewhere. If the result already contains a property with +// the same key, the value will be updated. +void UnitTest::RecordProperty(const std::string& key, + const std::string& value) { + impl_->RecordProperty(TestProperty(key, value)); } // Runs all tests in this UnitTest object and prints the result. @@ -3790,21 +4183,45 @@ void UnitTest::RecordPropertyForCurrentTest(const char* key, // We don't protect this under mutex_, as we only support calling it // from the main thread. int UnitTest::Run() { + const bool in_death_test_child_process = + internal::GTEST_FLAG(internal_run_death_test).length() > 0; + + // Google Test implements this protocol for catching that a test + // program exits before returning control to Google Test: + // + // 1. Upon start, Google Test creates a file whose absolute path + // is specified by the environment variable + // TEST_PREMATURE_EXIT_FILE. + // 2. When Google Test has finished its work, it deletes the file. + // + // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before + // running a Google-Test-based test program and check the existence + // of the file at the end of the test execution to see if it has + // exited prematurely. + + // If we are in the child process of a death test, don't + // create/delete the premature exit file, as doing so is unnecessary + // and will confuse the parent process. Otherwise, create/delete + // the file upon entering/leaving this function. If the program + // somehow exits before this function has a chance to return, the + // premature-exit file will be left undeleted, causing a test runner + // that understands the premature-exit-file protocol to report the + // test as having failed. + const internal::ScopedPrematureExitFile premature_exit_file( + in_death_test_child_process ? + NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); + // Captures the value of GTEST_FLAG(catch_exceptions). This value will be // used for the duration of the program. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); #if GTEST_HAS_SEH - const bool in_death_test_child_process = - internal::GTEST_FLAG(internal_run_death_test).length() > 0; - // Either the user wants Google Test to catch exceptions thrown by the // tests or this is executing in the context of death test child // process. In either case the user does not want to see pop-up dialogs // about crashes - they are expected. if (impl()->catch_exceptions() || in_death_test_child_process) { - -# if !GTEST_OS_WINDOWS_MOBILE +# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // SetErrorMode doesn't exist on CE. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); @@ -3834,7 +4251,6 @@ int UnitTest::Run() { 0x0, // Clear the following flags: _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. # endif - } #endif // GTEST_HAS_SEH @@ -3852,16 +4268,16 @@ const char* UnitTest::original_working_dir() const { // Returns the TestCase object for the test that's currently running, // or NULL if no test is running. -// L < mutex_ -const TestCase* UnitTest::current_test_case() const { +const TestCase* UnitTest::current_test_case() const + GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_case(); } // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. -// L < mutex_ -const TestInfo* UnitTest::current_test_info() const { +const TestInfo* UnitTest::current_test_info() const + GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_info(); } @@ -3872,9 +4288,9 @@ int UnitTest::random_seed() const { return impl_->random_seed(); } #if GTEST_HAS_PARAM_TEST // Returns ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. -// L < mutex_ internal::ParameterizedTestCaseRegistry& - UnitTest::parameterized_test_registry() { + UnitTest::parameterized_test_registry() + GTEST_LOCK_EXCLUDED_(mutex_) { return impl_->parameterized_test_registry(); } #endif // GTEST_HAS_PARAM_TEST @@ -3891,15 +4307,15 @@ UnitTest::~UnitTest() { // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. -// L < mutex_ -void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) { +void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) + GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().push_back(trace); } // Pops a trace from the per-thread Google Test trace stack. -// L < mutex_ -void UnitTest::PopGTestTrace() { +void UnitTest::PopGTestTrace() + GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().pop_back(); } @@ -3908,17 +4324,10 @@ namespace internal { UnitTestImpl::UnitTestImpl(UnitTest* parent) : parent_(parent), -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4355) // Temporarily disables warning 4355 - // (using this in initializer). + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */) default_global_test_part_result_reporter_(this), default_per_thread_test_part_result_reporter_(this), -# pragma warning(pop) // Restores the warning state again. -#else - default_global_test_part_result_reporter_(this), - default_per_thread_test_part_result_reporter_(this), -#endif // _MSC_VER + GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_( &default_global_test_part_result_reporter_), per_thread_test_part_result_reporter_( @@ -3935,9 +4344,9 @@ UnitTestImpl::UnitTestImpl(UnitTest* parent) post_flag_parse_init_performed_(false), random_seed_(0), // Will be overridden by the flag before first use. random_(0), // Will be reseeded before first use. + start_timestamp_(0), elapsed_time_(0), #if GTEST_HAS_DEATH_TEST - internal_run_death_test_flag_(NULL), death_test_factory_(new DefaultDeathTestFactory), #endif // Will be overridden by the flag before first use. @@ -3955,6 +4364,28 @@ UnitTestImpl::~UnitTestImpl() { delete os_stack_trace_getter_; } +// Adds a TestProperty to the current TestResult object when invoked in a +// context of a test, to current test case's ad_hoc_test_result when invoke +// from SetUpTestCase/TearDownTestCase, or to the global property set +// otherwise. If the result already contains a property with the same key, +// the value will be updated. +void UnitTestImpl::RecordProperty(const TestProperty& test_property) { + std::string xml_element; + TestResult* test_result; // TestResult appropriate for property recording. + + if (current_test_info_ != NULL) { + xml_element = "testcase"; + test_result = &(current_test_info_->result_); + } else if (current_test_case_ != NULL) { + xml_element = "testsuite"; + test_result = &(current_test_case_->ad_hoc_test_result_); + } else { + xml_element = "testsuites"; + test_result = &ad_hoc_test_result_; + } + test_result->RecordProperty(xml_element, test_property); +} + #if GTEST_HAS_DEATH_TEST // Disables event forwarding if the control is currently in a death test // subprocess. Must not be called before InitGoogleTest. @@ -3967,7 +4398,7 @@ void UnitTestImpl::SuppressTestEventsIfInSubprocess() { // Initializes event listeners performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureXmlOutput() { - const String& output_format = UnitTestOptions::GetOutputFormat(); + const std::string& output_format = UnitTestOptions::GetOutputFormat(); if (output_format == "xml") { listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); @@ -3979,13 +4410,13 @@ void UnitTestImpl::ConfigureXmlOutput() { } #if GTEST_CAN_STREAM_RESULTS_ -// Initializes event listeners for streaming test results in String form. +// Initializes event listeners for streaming test results in string form. // Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureStreamingOutput() { - const string& target = GTEST_FLAG(stream_result_to); + const std::string& target = GTEST_FLAG(stream_result_to); if (!target.empty()) { const size_t pos = target.find(':'); - if (pos != string::npos) { + if (pos != std::string::npos) { listeners()->Append(new StreamingListener(target.substr(0, pos), target.substr(pos+1))); } else { @@ -4007,6 +4438,11 @@ void UnitTestImpl::PostFlagParsingInit() { if (!post_flag_parse_init_performed_) { post_flag_parse_init_performed_ = true; +#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) + // Register to send notifications about key process state changes. + listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_()); +#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) + #if GTEST_HAS_DEATH_TEST InitDeathTestSubprocessControlInfo(); SuppressTestEventsIfInSubprocess(); @@ -4039,7 +4475,7 @@ void UnitTestImpl::PostFlagParsingInit() { class TestCaseNameIs { public: // Constructor. - explicit TestCaseNameIs(const String& name) + explicit TestCaseNameIs(const std::string& name) : name_(name) {} // Returns true iff the name of test_case matches name_. @@ -4048,7 +4484,7 @@ class TestCaseNameIs { } private: - String name_; + std::string name_; }; // Finds and returns a TestCase with the given name. If one doesn't @@ -4080,7 +4516,7 @@ TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); // Is this a death test case? - if (internal::UnitTestOptions::MatchesFilter(String(test_case_name), + if (internal::UnitTestOptions::MatchesFilter(test_case_name, kDeathTestCaseFilter)) { // Yes. Inserts the test case after the last death test case // defined so far. This only works when the test cases haven't @@ -4140,6 +4576,11 @@ bool UnitTestImpl::RunAllTests() { #if GTEST_HAS_DEATH_TEST in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); +# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) + if (in_subprocess_for_death_test) { + GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); + } +# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) #endif // GTEST_HAS_DEATH_TEST const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, @@ -4166,6 +4607,7 @@ bool UnitTestImpl::RunAllTests() { TestEventListener* repeater = listeners()->repeater(); + start_timestamp_ = GetTimeInMillis(); repeater->OnTestProgramStart(*parent_); // How many times to repeat the tests? We don't want to repeat them @@ -4358,12 +4800,12 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { int num_selected_tests = 0; for (size_t i = 0; i < test_cases_.size(); i++) { TestCase* const test_case = test_cases_[i]; - const String &test_case_name = test_case->name(); + const std::string &test_case_name = test_case->name(); test_case->set_should_run(false); for (size_t j = 0; j < test_case->test_info_list().size(); j++) { TestInfo* const test_info = test_case->test_info_list()[j]; - const String test_name(test_info->name()); + const std::string test_name(test_info->name()); // A test is disabled if test case name or test name matches // kDisableTestFilter. const bool is_disabled = @@ -4397,8 +4839,33 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { return num_selected_tests; } +// Prints the given C-string on a single line by replacing all '\n' +// characters with string "\\n". If the output takes more than +// max_length characters, only prints the first max_length characters +// and "...". +static void PrintOnOneLine(const char* str, int max_length) { + if (str != NULL) { + for (int i = 0; *str != '\0'; ++str) { + if (i >= max_length) { + printf("..."); + break; + } + if (*str == '\n') { + printf("\\n"); + i += 2; + } else { + printf("%c", *str); + ++i; + } + } + } +} + // Prints the names of the tests matching the user-specified filter flag. void UnitTestImpl::ListTestsMatchingFilter() { + // Print at most this many characters for each type/value parameter. + const int kMaxParamLength = 250; + for (size_t i = 0; i < test_cases_.size(); i++) { const TestCase* const test_case = test_cases_[i]; bool printed_test_case_name = false; @@ -4409,9 +4876,23 @@ void UnitTestImpl::ListTestsMatchingFilter() { if (test_info->matches_filter_) { if (!printed_test_case_name) { printed_test_case_name = true; - printf("%s.\n", test_case->name()); + printf("%s.", test_case->name()); + if (test_case->type_param() != NULL) { + printf(" # %s = ", kTypeParamLabel); + // We print the type parameter on a single line to make + // the output easy to parse by a program. + PrintOnOneLine(test_case->type_param(), kMaxParamLength); + } + printf("\n"); + } + printf(" %s", test_info->name()); + if (test_info->value_param() != NULL) { + printf(" # %s = ", kValueParamLabel); + // We print the value parameter on a single line to make the + // output easy to parse by a program. + PrintOnOneLine(test_info->value_param(), kMaxParamLength); } - printf(" %s\n", test_info->name()); + printf("\n"); } } } @@ -4436,7 +4917,11 @@ void UnitTestImpl::set_os_stack_trace_getter( // getter, and returns it. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { if (os_stack_trace_getter_ == NULL) { +#ifdef GTEST_OS_STACK_TRACE_GETTER_ + os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_; +#else os_stack_trace_getter_ = new OsStackTraceGetter; +#endif // GTEST_OS_STACK_TRACE_GETTER_ } return os_stack_trace_getter_; @@ -4475,7 +4960,7 @@ void UnitTestImpl::UnshuffleTests() { } } -// Returns the current OS stack trace as a String. +// Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter @@ -4485,8 +4970,8 @@ void UnitTestImpl::UnshuffleTests() { // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, - int skip_count) { +std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, + int skip_count) { // We pass skip_count + 1 to skip this wrapper function in addition // to what the user really wants to skip. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); @@ -4534,7 +5019,7 @@ const char* ParseFlagValue(const char* str, if (str == NULL || flag == NULL) return NULL; // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. - const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag); + const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; const size_t flag_len = flag_str.length(); if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; @@ -4599,7 +5084,7 @@ bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. -bool ParseStringFlag(const char* str, const char* flag, String* value) { +bool ParseStringFlag(const char* str, const char* flag, std::string* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); @@ -4651,7 +5136,7 @@ static void PrintColorEncoded(const char* str) { return; } - ColoredPrintf(color, "%s", String(str, p - str).c_str()); + ColoredPrintf(color, "%s", std::string(str, p).c_str()); const char ch = p[1]; str = p + 2; @@ -4735,48 +5220,89 @@ static const char kColorEncodedHelpMessage[] = "(not one in your own code or tests), please report it to\n" "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; +bool ParseGoogleTestFlag(const char* const arg) { + return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, + >EST_FLAG(also_run_disabled_tests)) || + ParseBoolFlag(arg, kBreakOnFailureFlag, + >EST_FLAG(break_on_failure)) || + ParseBoolFlag(arg, kCatchExceptionsFlag, + >EST_FLAG(catch_exceptions)) || + ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || + ParseStringFlag(arg, kDeathTestStyleFlag, + >EST_FLAG(death_test_style)) || + ParseBoolFlag(arg, kDeathTestUseFork, + >EST_FLAG(death_test_use_fork)) || + ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || + ParseStringFlag(arg, kInternalRunDeathTestFlag, + >EST_FLAG(internal_run_death_test)) || + ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || + ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || + ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || + ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || + ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || + ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || + ParseInt32Flag(arg, kStackTraceDepthFlag, + >EST_FLAG(stack_trace_depth)) || + ParseStringFlag(arg, kStreamResultToFlag, + >EST_FLAG(stream_result_to)) || + ParseBoolFlag(arg, kThrowOnFailureFlag, + >EST_FLAG(throw_on_failure)); +} + +#if GTEST_USE_OWN_FLAGFILE_FLAG_ +void LoadFlagsFromFile(const std::string& path) { + FILE* flagfile = posix::FOpen(path.c_str(), "r"); + if (!flagfile) { + fprintf(stderr, + "Unable to open file \"%s\"\n", + GTEST_FLAG(flagfile).c_str()); + fflush(stderr); + exit(EXIT_FAILURE); + } + std::string contents(ReadEntireFile(flagfile)); + posix::FClose(flagfile); + std::vector<std::string> lines; + SplitString(contents, '\n', &lines); + for (size_t i = 0; i < lines.size(); ++i) { + if (lines[i].empty()) + continue; + if (!ParseGoogleTestFlag(lines[i].c_str())) + g_help_flag = true; + } +} +#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ + // Parses the command line for Google Test flags, without initializing // other parts of Google Test. The type parameter CharType can be // instantiated to either char or wchar_t. template <typename CharType> void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { for (int i = 1; i < *argc; i++) { - const String arg_string = StreamableToString(argv[i]); + const std::string arg_string = StreamableToString(argv[i]); const char* const arg = arg_string.c_str(); using internal::ParseBoolFlag; using internal::ParseInt32Flag; using internal::ParseStringFlag; - // Do we see a Google Test flag? - if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, - >EST_FLAG(also_run_disabled_tests)) || - ParseBoolFlag(arg, kBreakOnFailureFlag, - >EST_FLAG(break_on_failure)) || - ParseBoolFlag(arg, kCatchExceptionsFlag, - >EST_FLAG(catch_exceptions)) || - ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || - ParseStringFlag(arg, kDeathTestStyleFlag, - >EST_FLAG(death_test_style)) || - ParseBoolFlag(arg, kDeathTestUseFork, - >EST_FLAG(death_test_use_fork)) || - ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || - ParseStringFlag(arg, kInternalRunDeathTestFlag, - >EST_FLAG(internal_run_death_test)) || - ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || - ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || - ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || - ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || - ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || - ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || - ParseInt32Flag(arg, kStackTraceDepthFlag, - >EST_FLAG(stack_trace_depth)) || - ParseStringFlag(arg, kStreamResultToFlag, - >EST_FLAG(stream_result_to)) || - ParseBoolFlag(arg, kThrowOnFailureFlag, - >EST_FLAG(throw_on_failure)) - ) { - // Yes. Shift the remainder of the argv list left by one. Note + bool remove_flag = false; + if (ParseGoogleTestFlag(arg)) { + remove_flag = true; +#if GTEST_USE_OWN_FLAGFILE_FLAG_ + } else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) { + LoadFlagsFromFile(GTEST_FLAG(flagfile)); + remove_flag = true; +#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ + } else if (arg_string == "--help" || arg_string == "-h" || + arg_string == "-?" || arg_string == "/?" || + HasGoogleTestFlagPrefix(arg)) { + // Both help flag and unrecognized Google Test flags (excluding + // internal ones) trigger help display. + g_help_flag = true; + } + + if (remove_flag) { + // Shift the remainder of the argv list left by one. Note // that argv has (*argc + 1) elements, the last one always being // NULL. The following loop moves the trailing NULL element as // well. @@ -4790,12 +5316,6 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { // We also need to decrement the iterator as we just removed // an element. i--; - } else if (arg_string == "--help" || arg_string == "-h" || - arg_string == "-?" || arg_string == "/?" || - HasGoogleTestFlagPrefix(arg)) { - // Both help flag and unrecognized Google Test flags (excluding - // internal ones) trigger help display. - g_help_flag = true; } } @@ -4822,24 +5342,16 @@ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { // wchar_t. template <typename CharType> void InitGoogleTestImpl(int* argc, CharType** argv) { - g_init_gtest_count++; - // We don't want to run the initialization code twice. - if (g_init_gtest_count != 1) return; + if (GTestIsInitialized()) return; if (*argc <= 0) return; - internal::g_executable_path = internal::StreamableToString(argv[0]); - -#if GTEST_HAS_DEATH_TEST - g_argvs.clear(); for (int i = 0; i != *argc; i++) { g_argvs.push_back(StreamableToString(argv[i])); } -#endif // GTEST_HAS_DEATH_TEST - ParseGoogleTestFlagsOnly(argc, argv); GetUnitTestImpl()->PostFlagParsingInit(); } @@ -4856,23 +5368,21 @@ void InitGoogleTestImpl(int* argc, CharType** argv) { // // Calling the function for the second time has no user-visible effect. void InitGoogleTest(int* argc, char** argv) { +#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) + GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); +#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); +#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } // This overloaded version can be used in Windows programs compiled in // UNICODE mode. void InitGoogleTest(int* argc, wchar_t** argv) { +#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) + GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); +#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); -} - -// Pin the vtables to this file. -Environment::~Environment() {} -TestPartResultReporterInterface::~TestPartResultReporterInterface() {} -TestEventListener::~TestEventListener() {} -void EmptyTestEventListener::anchor() {} -namespace internal { -OsStackTraceGetterInterface::~OsStackTraceGetterInterface() {} -ParameterizedTestCaseInfoBase::~ParameterizedTestCaseInfoBase() {} +#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } } // namespace testing diff --git a/gnu/llvm/utils/update_llc_test_checks.py b/gnu/llvm/utils/update_llc_test_checks.py index d2df5b6511e..d077c8a8eb2 100755 --- a/gnu/llvm/utils/update_llc_test_checks.py +++ b/gnu/llvm/utils/update_llc_test_checks.py @@ -8,12 +8,10 @@ a single test function. """ import argparse -import itertools import os # Used to advertise this file's name ("autogenerated_note"). import string import subprocess import sys -import tempfile import re # Invoke the tool that is being tested. @@ -30,6 +28,13 @@ def llc(args, cmd_args, ir): SCRUB_WHITESPACE_RE = re.compile(r'(?!^(| \w))[ \t]+', flags=re.M) SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M) +SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n') + +ASM_FUNCTION_X86_RE = re.compile( + r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@(?P=func)\n[^:]*?' + r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*' + r'^\s*(?:[^:\n]+?:\s*\n\s*\.size|\.cfi_endproc|\.globl|\.comm|\.(?:sub)?section)', + flags=(re.M | re.S)) SCRUB_X86_SHUFFLES_RE = ( re.compile( r'^(\s*\w+) [^#\n]+#+ ((?:[xyz]mm\d+|mem)( \{%k\d+\}( \{z\})?)? = .*)$', @@ -37,20 +42,34 @@ SCRUB_X86_SHUFFLES_RE = ( SCRUB_X86_SP_RE = re.compile(r'\d+\(%(esp|rsp)\)') SCRUB_X86_RIP_RE = re.compile(r'[.\w]+\(%rip\)') SCRUB_X86_LCP_RE = re.compile(r'\.LCPI[0-9]+_[0-9]+') -SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n') + +ASM_FUNCTION_ARM_RE = re.compile( + r'^(?P<func>[0-9a-zA-Z_]+):\n' # f: (name of function) + r'\s+\.fnstart\n' # .fnstart + r'(?P<body>.*?)\n' # (body of the function) + r'.Lfunc_end[0-9]+:\n', # .Lfunc_end0: + flags=(re.M | re.S)) RUN_LINE_RE = re.compile('^\s*;\s*RUN:\s*(.*)$') +TRIPLE_ARG_RE = re.compile(r'-mtriple=([^ ]+)') +TRIPLE_IR_RE = re.compile(r'^target\s+triple\s*=\s*"([^"]+)"$') IR_FUNCTION_RE = re.compile('^\s*define\s+(?:internal\s+)?[^@]*@(\w+)\s*\(') -ASM_FUNCTION_RE = re.compile( - r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@(?P=func)\n[^:]*?' - r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*' - r'^\s*(?:[^:\n]+?:\s*\n\s*\.size|\.cfi_endproc|\.globl|\.comm|\.(?:sub)?section)', - flags=(re.M | re.S)) CHECK_PREFIX_RE = re.compile('--check-prefix=(\S+)') CHECK_RE = re.compile(r'^\s*;\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:') +ASM_FUNCTION_PPC_RE = re.compile( + r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@(?P=func)\n' + r'\.Lfunc_begin[0-9]+:\n' + r'[ \t]+.cfi_startproc\n' + r'(?:\.Lfunc_[gl]ep[0-9]+:\n(?:[ \t]+.*?\n)*)*' + r'(?P<body>.*?)\n' + # This list is incomplete + r'(?:^[ \t]*(?:\.long[ \t]+[^\n]+|\.quad[ \t]+[^\n]+)\n)*' + r'.Lfunc_end[0-9]+:\n', + flags=(re.M | re.S)) + -def scrub_asm(asm): +def scrub_asm_x86(asm): # Scrub runs of whitespace out of the assembly, but leave the leading # whitespace in place. asm = SCRUB_WHITESPACE_RE.sub(r' ', asm) @@ -70,14 +89,54 @@ def scrub_asm(asm): asm = SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm) return asm +def scrub_asm_arm_eabi(asm): + # Scrub runs of whitespace out of the assembly, but leave the leading + # whitespace in place. + asm = SCRUB_WHITESPACE_RE.sub(r' ', asm) + # Expand the tabs used for indentation. + asm = string.expandtabs(asm, 2) + # Strip kill operands inserted into the asm. + asm = SCRUB_KILL_COMMENT_RE.sub('', asm) + # Strip trailing whitespace. + asm = SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm) + return asm + +def scrub_asm_powerpc64le(asm): + # Scrub runs of whitespace out of the assembly, but leave the leading + # whitespace in place. + asm = SCRUB_WHITESPACE_RE.sub(r' ', asm) + # Expand the tabs used for indentation. + asm = string.expandtabs(asm, 2) + # Strip trailing whitespace. + asm = SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm) + return asm + # Build up a dictionary of all the function bodies. -def build_function_body_dictionary(raw_tool_output, prefixes, func_dict, verbose): - for m in ASM_FUNCTION_RE.finditer(raw_tool_output): +def build_function_body_dictionary(raw_tool_output, triple, prefixes, func_dict, + verbose): + target_handlers = { + 'x86_64': (scrub_asm_x86, ASM_FUNCTION_X86_RE), + 'i686': (scrub_asm_x86, ASM_FUNCTION_X86_RE), + 'x86': (scrub_asm_x86, ASM_FUNCTION_X86_RE), + 'i386': (scrub_asm_x86, ASM_FUNCTION_X86_RE), + 'arm-eabi': (scrub_asm_arm_eabi, ASM_FUNCTION_ARM_RE), + 'powerpc64le': (scrub_asm_powerpc64le, ASM_FUNCTION_PPC_RE), + } + handlers = None + for prefix, s in target_handlers.items(): + if triple.startswith(prefix): + handlers = s + break + else: + raise KeyError('Triple %r is not supported' % (triple)) + + scrubber, function_re = handlers + for m in function_re.finditer(raw_tool_output): if not m: continue func = m.group('func') - scrubbed_body = scrub_asm(m.group('body')) + scrubbed_body = scrubber(m.group('body')) if func.startswith('stress'): # We only use the last line of the function body for stress tests. scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:]) @@ -97,9 +156,10 @@ def build_function_body_dictionary(raw_tool_output, prefixes, func_dict, verbose func_dict[prefix][func] = scrubbed_body -def add_checks(output_lines, prefix_list, func_dict, func_name): +def add_checks(output_lines, run_list, func_dict, func_name): printed_prefixes = [] - for checkprefixes, _ in prefix_list: + for p in run_list: + checkprefixes = p[0] for checkprefix in checkprefixes: if checkprefix in printed_prefixes: break @@ -155,16 +215,40 @@ def main(): with open(test) as f: input_lines = [l.rstrip() for l in f] - run_lines = [m.group(1) + triple_in_ir = None + for l in input_lines: + m = TRIPLE_IR_RE.match(l) + if m: + triple_in_ir = m.groups()[0] + break + + raw_lines = [m.group(1) for m in [RUN_LINE_RE.match(l) for l in input_lines] if m] + run_lines = [raw_lines[0]] if len(raw_lines) > 0 else [] + for l in raw_lines[1:]: + if run_lines[-1].endswith("\\"): + run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l + else: + run_lines.append(l) + if args.verbose: print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),) for l in run_lines: print >>sys.stderr, ' RUN: ' + l - prefix_list = [] + run_list = [] for l in run_lines: - (llc_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)]) + commands = [cmd.strip() for cmd in l.split('|', 1)] + llc_cmd = commands[0] + + triple_in_cmd = None + m = TRIPLE_ARG_RE.search(llc_cmd) + if m: + triple_in_cmd = m.groups()[0] + + filecheck_cmd = '' + if len(commands) > 1: + filecheck_cmd = commands[1] if not llc_cmd.startswith('llc '): print >>sys.stderr, 'WARNING: Skipping non-llc RUN line: ' + l continue @@ -183,23 +267,29 @@ def main(): # FIXME: We should use multiple check prefixes to common check lines. For # now, we just ignore all but the last. - prefix_list.append((check_prefixes, llc_cmd_args)) + run_list.append((check_prefixes, llc_cmd_args, triple_in_cmd)) func_dict = {} - for prefixes, _ in prefix_list: + for p in run_list: + prefixes = p[0] for prefix in prefixes: func_dict.update({prefix: dict()}) - for prefixes, llc_args in prefix_list: + for prefixes, llc_args, triple_in_cmd in run_list: if args.verbose: print >>sys.stderr, 'Extracted LLC cmd: llc ' + llc_args print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes) raw_tool_output = llc(args, llc_args, test) - build_function_body_dictionary(raw_tool_output, prefixes, func_dict, args.verbose) + if not (triple_in_cmd or triple_in_ir): + print >>sys.stderr, "Cannot find a triple. Assume 'x86'" + + build_function_body_dictionary(raw_tool_output, + triple_in_cmd or triple_in_ir or 'x86', prefixes, func_dict, args.verbose) is_in_function = False is_in_function_start = False - prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes]) + func_name = None + prefix_set = set([prefix for p in run_list for prefix in p[0]]) if args.verbose: print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,) output_lines = [] @@ -216,7 +306,7 @@ def main(): continue # Print out the various check lines here. - output_lines = add_checks(output_lines, prefix_list, func_dict, name) + output_lines = add_checks(output_lines, run_list, func_dict, func_name) is_in_function_start = False if is_in_function: @@ -238,8 +328,8 @@ def main(): m = IR_FUNCTION_RE.match(input_line) if not m: continue - name = m.group(1) - if args.function is not None and name != args.function: + func_name = m.group(1) + if args.function is not None and func_name != args.function: # When filtering on a specific function, skip all others. continue is_in_function = is_in_function_start = True diff --git a/gnu/llvm/utils/update_test_checks.py b/gnu/llvm/utils/update_test_checks.py index c084debbe98..92ab5ef6599 100755 --- a/gnu/llvm/utils/update_test_checks.py +++ b/gnu/llvm/utils/update_test_checks.py @@ -64,11 +64,13 @@ LLC_FUNCTION_RE = re.compile( flags=(re.M | re.S)) OPT_FUNCTION_RE = re.compile( r'^\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[\w-]+?)\s*\(' - r'(\s+)?[^{]*\{\n(?P<body>.*?)\}', + r'(\s+)?[^)]*[^{]*\{\n(?P<body>.*?)^\}$', flags=(re.M | re.S)) CHECK_PREFIX_RE = re.compile('--check-prefix=(\S+)') CHECK_RE = re.compile(r'^\s*;\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:') -IR_VALUE_DEF_RE = re.compile(r'\s+%(.*) =') +# Match things that look at identifiers, but only if they are followed by +# spaces, commas, paren, or end of the string +IR_VALUE_RE = re.compile(r'(\s+)%(.+?)([,\s\(\)]|\Z)') # Invoke the tool that is being tested. @@ -156,33 +158,34 @@ def get_value_definition(var): def get_value_use(var): return '[[' + get_value_name(var) + ']]' - # Replace IR value defs and uses with FileCheck variables. def genericize_check_lines(lines): + # This gets called for each match that occurs in + # a line. We transform variables we haven't seen + # into defs, and variables we have seen into uses. + def transform_line_vars(match): + var = match.group(2) + if var in vars_seen: + rv = get_value_use(var) + else: + vars_seen.add(var) + rv = get_value_definition(var) + # re.sub replaces the entire regex match + # with whatever you return, so we have + # to make sure to hand it back everything + # including the commas and spaces. + return match.group(1) + rv + match.group(3) + + vars_seen = set() lines_with_def = [] - vars_seen = [] - for line in lines: + + for i, line in enumerate(lines): # An IR variable named '%.' matches the FileCheck regex string. line = line.replace('%.', '%dot') - m = IR_VALUE_DEF_RE.match(line) - if m: - vars_seen.append(m.group(1)) - line = line.replace('%' + m.group(1), get_value_definition(m.group(1))) - - lines_with_def.append(line) - - # A single def isn't worth replacing? - #if len(vars_seen) < 2: - # return lines - - output_lines = [] - vars_seen.sort(key=len, reverse=True) - for line in lines_with_def: - for var in vars_seen: - line = line.replace('%' + var, get_value_use(var)) - output_lines.append(line) - - return output_lines + # Ignore any comments, since the check lines will too. + scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line) + lines[i] = IR_VALUE_RE.sub(transform_line_vars, scrubbed_line) + return lines def add_checks(output_lines, prefix_list, func_dict, func_name, tool_basename): @@ -292,8 +295,15 @@ def main(): with open(test) as f: input_lines = [l.rstrip() for l in f] - run_lines = [m.group(1) + raw_lines = [m.group(1) for m in [RUN_LINE_RE.match(l) for l in input_lines] if m] + run_lines = [raw_lines[0]] if len(raw_lines) > 0 else [] + for l in raw_lines[1:]: + if run_lines[-1].endswith("\\"): + run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l + else: + run_lines.append(l) + if args.verbose: print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),) for l in run_lines: diff --git a/gnu/llvm/utils/vim/syntax/llvm.vim b/gnu/llvm/utils/vim/syntax/llvm.vim index e9e3596ecbd..ca3e2ffc9be 100644 --- a/gnu/llvm/utils/vim/syntax/llvm.vim +++ b/gnu/llvm/utils/vim/syntax/llvm.vim @@ -1,7 +1,7 @@ " Vim syntax file " Language: llvm " Maintainer: The LLVM team, http://llvm.org/ -" Version: $Revision: 1.1.1.2 $ +" Version: $Revision: 1.1.1.3 $ if version < 600 syntax clear @@ -23,7 +23,8 @@ syn match llvmType /\<i\d\+\>/ " The true and false tokens can be used for comparison opcodes, but it's " much more common for these tokens to be used for boolean constants. syn keyword llvmStatement add addrspacecast alloca and arcp ashr atomicrmw -syn keyword llvmStatement bitcast br call cmpxchg eq exact extractelement +syn keyword llvmStatement bitcast br catchpad catchswitch catchret call +syn keyword llvmStatement cleanuppad cleanupret cmpxchg eq exact extractelement syn keyword llvmStatement extractvalue fadd fast fcmp fdiv fence fmul fpext syn keyword llvmStatement fptosi fptoui fptrunc free frem fsub getelementptr syn keyword llvmStatement icmp inbounds indirectbr insertelement insertvalue @@ -45,6 +46,7 @@ syn keyword llvmKeyword \ alignstack \ alwaysinline \ appending + \ argmemonly \ arm_aapcscc \ arm_aapcs_vfpcc \ arm_apcscc @@ -55,10 +57,12 @@ syn keyword llvmKeyword \ byval \ c \ catch + \ caller \ cc \ ccc \ cleanup \ coldcc + \ comdat \ common \ constant \ datalayout @@ -66,6 +70,7 @@ syn keyword llvmKeyword \ default \ define \ deplibs + \ dereferenceable \ distinct \ dllexport \ dllimport @@ -75,6 +80,7 @@ syn keyword llvmKeyword \ extern_weak \ fastcc \ filter + \ from \ gc \ global \ hhvmcc @@ -103,6 +109,7 @@ syn keyword llvmKeyword \ noimplicitfloat \ noinline \ nonlazybind + \ norecurse \ noredzone \ noreturn \ nounwind @@ -146,6 +153,8 @@ syn keyword llvmKeyword \ volatile \ weak \ weak_odr + \ within + \ writeonly \ x86_64_sysvcc \ x86_64_win64cc \ x86_fastcallcc @@ -162,7 +171,7 @@ syn match llvmNumber /-\?\<\d\+\>/ syn match llvmFloat /-\?\<\d\+\.\d*\(e[+-]\d\+\)\?\>/ syn match llvmFloat /\<0x\x\+\>/ syn keyword llvmBoolean true false -syn keyword llvmConstant zeroinitializer undef null +syn keyword llvmConstant zeroinitializer undef null none syn match llvmComment /;.*$/ syn region llvmString start=/"/ skip=/\\"/ end=/"/ syn match llvmLabel /[-a-zA-Z$._][-a-zA-Z$._0-9]*:/ @@ -183,6 +192,7 @@ syn match llvmConstant /\<DIFlag[A-Za-z]\+\>/ syn match llvmSpecialComment /;\s*PR\d*\s*$/ syn match llvmSpecialComment /;\s*REQUIRES:.*$/ syn match llvmSpecialComment /;\s*RUN:.*$/ +syn match llvmSpecialComment /;\s*CHECK:.*$/ syn match llvmSpecialComment /;\s*XFAIL:.*$/ if version >= 508 || !exists("did_c_syn_inits") diff --git a/gnu/llvm/utils/yaml-bench/YAMLBench.cpp b/gnu/llvm/utils/yaml-bench/YAMLBench.cpp index 634622a710c..721eeeecfd9 100644 --- a/gnu/llvm/utils/yaml-bench/YAMLBench.cpp +++ b/gnu/llvm/utils/yaml-bench/YAMLBench.cpp @@ -143,10 +143,10 @@ static void dumpStream(yaml::Stream &stream) { } } -static void benchmark( llvm::TimerGroup &Group - , llvm::StringRef Name - , llvm::StringRef JSONText) { - llvm::Timer BaseLine((Name + ": Loop").str(), Group); +static void benchmark(llvm::TimerGroup &Group, llvm::StringRef Name, + llvm::StringRef Description, llvm::StringRef JSONText) { + llvm::Timer BaseLine((Name + ".loop").str(), (Description + ": Loop").str(), + Group); BaseLine.startTimer(); char C = 0; for (llvm::StringRef::iterator I = JSONText.begin(), @@ -155,14 +155,16 @@ static void benchmark( llvm::TimerGroup &Group BaseLine.stopTimer(); volatile char DontOptimizeOut = C; (void)DontOptimizeOut; - llvm::Timer Tokenizing((Name + ": Tokenizing").str(), Group); + llvm::Timer Tokenizing((Name + ".tokenizing").str(), + (Description + ": Tokenizing").str(), Group); Tokenizing.startTimer(); { yaml::scanTokens(JSONText); } Tokenizing.stopTimer(); - llvm::Timer Parsing((Name + ": Parsing").str(), Group); + llvm::Timer Parsing((Name + ".parsing").str(), + (Description + ": Parsing").str(), Group); Parsing.startTimer(); { llvm::SourceMgr SM; @@ -218,13 +220,15 @@ int main(int argc, char **argv) { } if (Verify) { - llvm::TimerGroup Group("YAML parser benchmark"); - benchmark(Group, "Fast", createJSONText(10, 500)); + llvm::TimerGroup Group("yaml", "YAML parser benchmark"); + benchmark(Group, "Fast", "Fast", createJSONText(10, 500)); } else if (!DumpCanonical && !DumpTokens) { - llvm::TimerGroup Group("YAML parser benchmark"); - benchmark(Group, "Small Values", createJSONText(MemoryLimitMB, 5)); - benchmark(Group, "Medium Values", createJSONText(MemoryLimitMB, 500)); - benchmark(Group, "Large Values", createJSONText(MemoryLimitMB, 50000)); + llvm::TimerGroup Group("yaml", "YAML parser benchmark"); + benchmark(Group, "Small", "Small Values", createJSONText(MemoryLimitMB, 5)); + benchmark(Group, "Medium", "Medium Values", + createJSONText(MemoryLimitMB, 500)); + benchmark(Group, "Large", "Large Values", + createJSONText(MemoryLimitMB, 50000)); } return 0; |