head	1.1;
branch	1.1.1;
access;
symbols
	netbsd-11-0-RC4:1.1.1.9
	netbsd-11-0-RC3:1.1.1.9
	netbsd-11-0-RC2:1.1.1.9
	netbsd-11-0-RC1:1.1.1.9
	perseant-exfatfs-base-20250801:1.1.1.9
	netbsd-11:1.1.1.9.0.10
	netbsd-11-base:1.1.1.9
	netbsd-10-1-RELEASE:1.1.1.9
	perseant-exfatfs-base-20240630:1.1.1.9
	perseant-exfatfs:1.1.1.9.0.8
	perseant-exfatfs-base:1.1.1.9
	netbsd-8-3-RELEASE:1.1.1.6
	netbsd-9-4-RELEASE:1.1.1.8
	netbsd-10-0-RELEASE:1.1.1.9
	netbsd-10-0-RC6:1.1.1.9
	netbsd-10-0-RC5:1.1.1.9
	netbsd-10-0-RC4:1.1.1.9
	netbsd-10-0-RC3:1.1.1.9
	netbsd-10-0-RC2:1.1.1.9
	netbsd-10-0-RC1:1.1.1.9
	netbsd-10:1.1.1.9.0.6
	netbsd-10-base:1.1.1.9
	netbsd-9-3-RELEASE:1.1.1.8
	cjep_sun2x:1.1.1.9.0.4
	cjep_sun2x-base:1.1.1.9
	cjep_staticlib_x-base1:1.1.1.9
	netbsd-9-2-RELEASE:1.1.1.8
	cjep_staticlib_x:1.1.1.9.0.2
	cjep_staticlib_x-base:1.1.1.9
	netbsd-9-1-RELEASE:1.1.1.8
	phil-wifi-20200421:1.1.1.9
	phil-wifi-20200411:1.1.1.9
	phil-wifi-20200406:1.1.1.9
	netbsd-8-2-RELEASE:1.1.1.6
	netbsd-9-0-RELEASE:1.1.1.8
	netbsd-9-0-RC2:1.1.1.8
	netbsd-9-0-RC1:1.1.1.8
	netbsd-9:1.1.1.8.0.2
	netbsd-9-base:1.1.1.8
	phil-wifi-20190609:1.1.1.8
	netbsd-8-1-RELEASE:1.1.1.6
	netbsd-8-1-RC1:1.1.1.6
	pgoyette-compat-merge-20190127:1.1.1.7.2.1
	pgoyette-compat-20190127:1.1.1.8
	pgoyette-compat-20190118:1.1.1.8
	pgoyette-compat-1226:1.1.1.8
	pgoyette-compat-1126:1.1.1.8
	pgoyette-compat-1020:1.1.1.8
	pgoyette-compat-0930:1.1.1.8
	pgoyette-compat-0906:1.1.1.8
	netbsd-7-2-RELEASE:1.1.1.4
	pgoyette-compat-0728:1.1.1.8
	clang-337282:1.1.1.8
	netbsd-8-0-RELEASE:1.1.1.6
	phil-wifi:1.1.1.7.0.4
	phil-wifi-base:1.1.1.7
	pgoyette-compat-0625:1.1.1.7
	netbsd-8-0-RC2:1.1.1.6
	pgoyette-compat-0521:1.1.1.7
	pgoyette-compat-0502:1.1.1.7
	pgoyette-compat-0422:1.1.1.7
	netbsd-8-0-RC1:1.1.1.6
	pgoyette-compat-0415:1.1.1.7
	pgoyette-compat-0407:1.1.1.7
	pgoyette-compat-0330:1.1.1.7
	pgoyette-compat-0322:1.1.1.7
	pgoyette-compat-0315:1.1.1.7
	netbsd-7-1-2-RELEASE:1.1.1.4
	pgoyette-compat:1.1.1.7.0.2
	pgoyette-compat-base:1.1.1.7
	netbsd-7-1-1-RELEASE:1.1.1.4
	clang-319952:1.1.1.7
	matt-nb8-mediatek:1.1.1.6.0.10
	matt-nb8-mediatek-base:1.1.1.6
	clang-309604:1.1.1.7
	perseant-stdc-iso10646:1.1.1.6.0.8
	perseant-stdc-iso10646-base:1.1.1.6
	netbsd-8:1.1.1.6.0.6
	netbsd-8-base:1.1.1.6
	prg-localcount2-base3:1.1.1.6
	prg-localcount2-base2:1.1.1.6
	prg-localcount2-base1:1.1.1.6
	prg-localcount2:1.1.1.6.0.4
	prg-localcount2-base:1.1.1.6
	pgoyette-localcount-20170426:1.1.1.6
	bouyer-socketcan-base1:1.1.1.6
	pgoyette-localcount-20170320:1.1.1.6
	netbsd-7-1:1.1.1.4.0.10
	netbsd-7-1-RELEASE:1.1.1.4
	netbsd-7-1-RC2:1.1.1.4
	clang-294123:1.1.1.6
	netbsd-7-nhusb-base-20170116:1.1.1.4
	bouyer-socketcan:1.1.1.6.0.2
	bouyer-socketcan-base:1.1.1.6
	clang-291444:1.1.1.6
	pgoyette-localcount-20170107:1.1.1.5
	netbsd-7-1-RC1:1.1.1.4
	pgoyette-localcount-20161104:1.1.1.5
	netbsd-7-0-2-RELEASE:1.1.1.4
	localcount-20160914:1.1.1.5
	netbsd-7-nhusb:1.1.1.4.0.8
	netbsd-7-nhusb-base:1.1.1.4
	clang-280599:1.1.1.5
	pgoyette-localcount-20160806:1.1.1.5
	pgoyette-localcount-20160726:1.1.1.5
	pgoyette-localcount:1.1.1.5.0.2
	pgoyette-localcount-base:1.1.1.5
	netbsd-7-0-1-RELEASE:1.1.1.4
	clang-261930:1.1.1.5
	netbsd-7-0:1.1.1.4.0.6
	netbsd-7-0-RELEASE:1.1.1.4
	netbsd-7-0-RC3:1.1.1.4
	netbsd-7-0-RC2:1.1.1.4
	netbsd-7-0-RC1:1.1.1.4
	clang-237755:1.1.1.4
	clang-232565:1.1.1.4
	clang-227398:1.1.1.4
	tls-maxphys-base:1.1.1.4
	tls-maxphys:1.1.1.4.0.4
	netbsd-7:1.1.1.4.0.2
	netbsd-7-base:1.1.1.4
	clang-215315:1.1.1.4
	clang-209886:1.1.1.3
	yamt-pagecache:1.1.1.2.0.4
	yamt-pagecache-base9:1.1.1.2
	tls-earlyentropy:1.1.1.2.0.2
	tls-earlyentropy-base:1.1.1.3
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.1.1.2
	riastradh-drm2-base3:1.1.1.2
	clang-202566:1.1.1.2
	clang-201163:1.1.1.2
	clang-199312:1.1.1.1
	clang-198450:1.1.1.1
	clang-196603:1.1.1.1
	clang-195771:1.1.1.1
	LLVM:1.1.1;
locks; strict;
comment	@// @;


1.1
date	2013.11.28.14.14.48;	author joerg;	state Exp;
branches
	1.1.1.1;
next	;
commitid	ow8OybrawrB1f3fx;

1.1.1.1
date	2013.11.28.14.14.48;	author joerg;	state Exp;
branches;
next	1.1.1.2;
commitid	ow8OybrawrB1f3fx;

1.1.1.2
date	2014.02.14.20.07.03;	author joerg;	state Exp;
branches
	1.1.1.2.2.1
	1.1.1.2.4.1;
next	1.1.1.3;
commitid	annVkZ1sc17rF6px;

1.1.1.3
date	2014.05.30.18.14.50;	author joerg;	state Exp;
branches;
next	1.1.1.4;
commitid	8q0kdlBlCn09GACx;

1.1.1.4
date	2014.08.10.17.08.25;	author joerg;	state Exp;
branches
	1.1.1.4.4.1;
next	1.1.1.5;
commitid	N85tXAN6Ex9VZPLx;

1.1.1.5
date	2016.02.27.22.11.44;	author joerg;	state Exp;
branches
	1.1.1.5.2.1;
next	1.1.1.6;
commitid	tIimz3oDlh1NpBWy;

1.1.1.6
date	2017.01.11.10.33.10;	author joerg;	state Exp;
branches;
next	1.1.1.7;
commitid	CNnUNfII1jgNmxBz;

1.1.1.7
date	2017.08.01.19.34.43;	author joerg;	state Exp;
branches
	1.1.1.7.2.1
	1.1.1.7.4.1;
next	1.1.1.8;
commitid	pMuDy65V0VicSx1A;

1.1.1.8
date	2018.07.17.18.32.14;	author joerg;	state Exp;
branches;
next	1.1.1.9;
commitid	wDzL46ALjrCZgwKA;

1.1.1.9
date	2019.11.13.22.23.11;	author joerg;	state dead;
branches;
next	;
commitid	QD8YATxuNG34YJKB;

1.1.1.2.2.1
date	2014.08.10.07.08.25;	author tls;	state Exp;
branches;
next	;
commitid	t01A1TLTYxkpGMLx;

1.1.1.2.4.1
date	2014.02.14.20.07.03;	author yamt;	state dead;
branches;
next	1.1.1.2.4.2;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.2.4.2
date	2014.05.22.16.19.49;	author yamt;	state Exp;
branches;
next	;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.4.4.1
date	2014.08.10.17.08.25;	author tls;	state dead;
branches;
next	1.1.1.4.4.2;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.4.4.2
date	2014.08.19.23.49.28;	author tls;	state Exp;
branches;
next	;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.5.2.1
date	2017.03.20.06.53.39;	author pgoyette;	state Exp;
branches;
next	;
commitid	jjw7cAwgyKq7RfKz;

1.1.1.7.2.1
date	2018.07.28.04.34.19;	author pgoyette;	state Exp;
branches;
next	;
commitid	1UP1xAIUxv1ZgRLA;

1.1.1.7.4.1
date	2019.06.10.21.46.47;	author christos;	state Exp;
branches;
next	1.1.1.7.4.2;
commitid	jtc8rnCzWiEEHGqB;

1.1.1.7.4.2
date	2020.04.13.07.50.39;	author martin;	state dead;
branches;
next	;
commitid	X01YhRUPVUDaec4C;


desc
@@


1.1
log
@Initial revision
@
text
@//===- unittest/Tooling/CompilationDatabaseTest.cpp -----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/FileMatchTrie.h"
#include "clang/Tooling/JSONCompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/Path.h"
#include "gtest/gtest.h"

namespace clang {
namespace tooling {

static void expectFailure(StringRef JSONDatabase, StringRef Explanation) {
  std::string ErrorMessage;
  EXPECT_EQ(NULL, JSONCompilationDatabase::loadFromBuffer(JSONDatabase,
                                                          ErrorMessage))
    << "Expected an error because of: " << Explanation;
}

TEST(JSONCompilationDatabase, ErrsOnInvalidFormat) {
  expectFailure("", "Empty database");
  expectFailure("{", "Invalid JSON");
  expectFailure("[[]]", "Array instead of object");
  expectFailure("[{\"a\":[]}]", "Array instead of value");
  expectFailure("[{\"a\":\"b\"}]", "Unknown key");
  expectFailure("[{[]:\"\"}]", "Incorrectly typed entry");
  expectFailure("[{}]", "Empty entry");
  expectFailure("[{\"directory\":\"\",\"command\":\"\"}]", "Missing file");
  expectFailure("[{\"directory\":\"\",\"file\":\"\"}]", "Missing command");
  expectFailure("[{\"command\":\"\",\"file\":\"\"}]", "Missing directory");
}

static std::vector<std::string> getAllFiles(StringRef JSONDatabase,
                                            std::string &ErrorMessage) {
  OwningPtr<CompilationDatabase> Database(
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
  if (!Database) {
    ADD_FAILURE() << ErrorMessage;
    return std::vector<std::string>();
  }
  return Database->getAllFiles();
}

static std::vector<CompileCommand> getAllCompileCommands(StringRef JSONDatabase,
                                                    std::string &ErrorMessage) {
  OwningPtr<CompilationDatabase> Database(
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
  if (!Database) {
    ADD_FAILURE() << ErrorMessage;
    return std::vector<CompileCommand>();
  }
  return Database->getAllCompileCommands();
}

TEST(JSONCompilationDatabase, GetAllFiles) {
  std::string ErrorMessage;
  EXPECT_EQ(std::vector<std::string>(),
            getAllFiles("[]", ErrorMessage)) << ErrorMessage;

  std::vector<std::string> expected_files;
  SmallString<16> PathStorage;
  llvm::sys::path::native("//net/dir/file1", PathStorage);
  expected_files.push_back(PathStorage.str());
  llvm::sys::path::native("//net/dir/file2", PathStorage);
  expected_files.push_back(PathStorage.str());
  EXPECT_EQ(expected_files, getAllFiles(
    "[{\"directory\":\"//net/dir\","
      "\"command\":\"command\","
      "\"file\":\"file1\"},"
    " {\"directory\":\"//net/dir\","
      "\"command\":\"command\","
      "\"file\":\"file2\"}]",
    ErrorMessage)) << ErrorMessage;
}

TEST(JSONCompilationDatabase, GetAllCompileCommands) {
  std::string ErrorMessage;
  EXPECT_EQ(0u,
            getAllCompileCommands("[]", ErrorMessage).size()) << ErrorMessage;

  StringRef Directory1("//net/dir1");
  StringRef FileName1("file1");
  StringRef Command1("command1");
  StringRef Directory2("//net/dir2");
  StringRef FileName2("file1");
  StringRef Command2("command1");

  std::vector<CompileCommand> Commands = getAllCompileCommands(
      ("[{\"directory\":\"" + Directory1 + "\"," +
             "\"command\":\"" + Command1 + "\","
             "\"file\":\"" + FileName1 + "\"},"
       " {\"directory\":\"" + Directory2 + "\"," +
             "\"command\":\"" + Command2 + "\","
             "\"file\":\"" + FileName2 + "\"}]").str(),
      ErrorMessage);
  EXPECT_EQ(2U, Commands.size()) << ErrorMessage;
  EXPECT_EQ(Directory1, Commands[0].Directory) << ErrorMessage;
  ASSERT_EQ(1u, Commands[0].CommandLine.size());
  EXPECT_EQ(Command1, Commands[0].CommandLine[0]) << ErrorMessage;
  EXPECT_EQ(Directory2, Commands[1].Directory) << ErrorMessage;
  ASSERT_EQ(1u, Commands[1].CommandLine.size());
  EXPECT_EQ(Command2, Commands[1].CommandLine[0]) << ErrorMessage;
}

static CompileCommand findCompileArgsInJsonDatabase(StringRef FileName,
                                                    StringRef JSONDatabase,
                                                    std::string &ErrorMessage) {
  OwningPtr<CompilationDatabase> Database(
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
  if (!Database)
    return CompileCommand();
  std::vector<CompileCommand> Commands = Database->getCompileCommands(FileName);
  EXPECT_LE(Commands.size(), 1u);
  if (Commands.empty())
    return CompileCommand();
  return Commands[0];
}

struct FakeComparator : public PathComparator {
  virtual ~FakeComparator() {}
  virtual bool equivalent(StringRef FileA, StringRef FileB) const {
    return FileA.equals_lower(FileB);
  }
};

class FileMatchTrieTest : public ::testing::Test {
protected:
  FileMatchTrieTest() : Trie(new FakeComparator()) {}

  StringRef find(StringRef Path) {
    llvm::raw_string_ostream ES(Error);
    return Trie.findEquivalent(Path, ES);
  }

  FileMatchTrie Trie;
  std::string Error;
};

TEST_F(FileMatchTrieTest, InsertingRelativePath) {
  Trie.insert("//net/path/file.cc");
  Trie.insert("file.cc");
  EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
}

TEST_F(FileMatchTrieTest, MatchingRelativePath) {
  EXPECT_EQ("", find("file.cc"));
}

TEST_F(FileMatchTrieTest, ReturnsBestResults) {
  Trie.insert("//net/d/c/b.cc");
  Trie.insert("//net/d/b/b.cc");
  EXPECT_EQ("//net/d/b/b.cc", find("//net/d/b/b.cc"));
}

TEST_F(FileMatchTrieTest, HandlesSymlinks) {
  Trie.insert("//net/AA/file.cc");
  EXPECT_EQ("//net/AA/file.cc", find("//net/aa/file.cc"));
}

TEST_F(FileMatchTrieTest, ReportsSymlinkAmbiguity) {
  Trie.insert("//net/Aa/file.cc");
  Trie.insert("//net/aA/file.cc");
  EXPECT_TRUE(find("//net/aa/file.cc").empty());
  EXPECT_EQ("Path is ambiguous", Error);
}

TEST_F(FileMatchTrieTest, LongerMatchingSuffixPreferred) {
  Trie.insert("//net/src/Aa/file.cc");
  Trie.insert("//net/src/aA/file.cc");
  Trie.insert("//net/SRC/aa/file.cc");
  EXPECT_EQ("//net/SRC/aa/file.cc", find("//net/src/aa/file.cc"));
}

TEST_F(FileMatchTrieTest, EmptyTrie) {
  EXPECT_TRUE(find("//net/some/path").empty());
}

TEST_F(FileMatchTrieTest, NoResult) {
  Trie.insert("//net/somepath/otherfile.cc");
  Trie.insert("//net/otherpath/somefile.cc");
  EXPECT_EQ("", find("//net/somepath/somefile.cc"));
}

TEST_F(FileMatchTrieTest, RootElementDifferent) {
  Trie.insert("//net/path/file.cc");
  Trie.insert("//net/otherpath/file.cc");
  EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
}

TEST_F(FileMatchTrieTest, CannotResolveRelativePath) {
  EXPECT_EQ("", find("relative-path.cc"));
  EXPECT_EQ("Cannot resolve relative paths", Error);
}

TEST(findCompileArgsInJsonDatabase, FindsNothingIfEmpty) {
  std::string ErrorMessage;
  CompileCommand NotFound = findCompileArgsInJsonDatabase(
    "a-file.cpp", "", ErrorMessage);
  EXPECT_TRUE(NotFound.CommandLine.empty()) << ErrorMessage;
  EXPECT_TRUE(NotFound.Directory.empty()) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, ReadsSingleEntry) {
  StringRef Directory("//net/some/directory");
  StringRef FileName("//net/path/to/a-file.cpp");
  StringRef Command("//net/path/to/compiler and some arguments");
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    FileName,
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
  ASSERT_EQ(4u, FoundCommand.CommandLine.size()) << ErrorMessage;
  EXPECT_EQ("//net/path/to/compiler",
            FoundCommand.CommandLine[0]) << ErrorMessage;
  EXPECT_EQ("and", FoundCommand.CommandLine[1]) << ErrorMessage;
  EXPECT_EQ("some", FoundCommand.CommandLine[2]) << ErrorMessage;
  EXPECT_EQ("arguments", FoundCommand.CommandLine[3]) << ErrorMessage;

  CompileCommand NotFound = findCompileArgsInJsonDatabase(
    "a-file.cpp",
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  EXPECT_TRUE(NotFound.Directory.empty()) << ErrorMessage;
  EXPECT_TRUE(NotFound.CommandLine.empty()) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, ReadsCompileCommandLinesWithSpaces) {
  StringRef Directory("//net/some/directory");
  StringRef FileName("//net/path/to/a-file.cpp");
  StringRef Command("\\\"//net/path to compiler\\\" \\\"and an argument\\\"");
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    FileName,
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  ASSERT_EQ(2u, FoundCommand.CommandLine.size());
  EXPECT_EQ("//net/path to compiler",
            FoundCommand.CommandLine[0]) << ErrorMessage;
  EXPECT_EQ("and an argument", FoundCommand.CommandLine[1]) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, ReadsDirectoryWithSpaces) {
  StringRef Directory("//net/some directory / with spaces");
  StringRef FileName("//net/path/to/a-file.cpp");
  StringRef Command("a command");
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    FileName,
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, FindsEntry) {
  StringRef Directory("//net/directory");
  StringRef FileName("file");
  StringRef Command("command");
  std::string JsonDatabase = "[";
  for (int I = 0; I < 10; ++I) {
    if (I > 0) JsonDatabase += ",";
    JsonDatabase +=
      ("{\"directory\":\"" + Directory + Twine(I) + "\"," +
        "\"command\":\"" + Command + Twine(I) + "\","
        "\"file\":\"" + FileName + Twine(I) + "\"}").str();
  }
  JsonDatabase += "]";
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    "//net/directory4/file4", JsonDatabase, ErrorMessage);
  EXPECT_EQ("//net/directory4", FoundCommand.Directory) << ErrorMessage;
  ASSERT_EQ(1u, FoundCommand.CommandLine.size()) << ErrorMessage;
  EXPECT_EQ("command4", FoundCommand.CommandLine[0]) << ErrorMessage;
}

static std::vector<std::string> unescapeJsonCommandLine(StringRef Command) {
  std::string JsonDatabase =
    ("[{\"directory\":\"//net/root\", \"file\":\"test\", \"command\": \"" +
     Command + "\"}]").str();
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    "//net/root/test", JsonDatabase, ErrorMessage);
  EXPECT_TRUE(ErrorMessage.empty()) << ErrorMessage;
  return FoundCommand.CommandLine;
}

TEST(unescapeJsonCommandLine, ReturnsEmptyArrayOnEmptyString) {
  std::vector<std::string> Result = unescapeJsonCommandLine("");
  EXPECT_TRUE(Result.empty());
}

TEST(unescapeJsonCommandLine, SplitsOnSpaces) {
  std::vector<std::string> Result = unescapeJsonCommandLine("a b c");
  ASSERT_EQ(3ul, Result.size());
  EXPECT_EQ("a", Result[0]);
  EXPECT_EQ("b", Result[1]);
  EXPECT_EQ("c", Result[2]);
}

TEST(unescapeJsonCommandLine, MungesMultipleSpaces) {
  std::vector<std::string> Result = unescapeJsonCommandLine("   a   b   ");
  ASSERT_EQ(2ul, Result.size());
  EXPECT_EQ("a", Result[0]);
  EXPECT_EQ("b", Result[1]);
}

TEST(unescapeJsonCommandLine, UnescapesBackslashCharacters) {
  std::vector<std::string> Backslash = unescapeJsonCommandLine("a\\\\\\\\");
  ASSERT_EQ(1ul, Backslash.size());
  EXPECT_EQ("a\\", Backslash[0]);
  std::vector<std::string> Quote = unescapeJsonCommandLine("a\\\\\\\"");
  ASSERT_EQ(1ul, Quote.size());
  EXPECT_EQ("a\"", Quote[0]);
}

TEST(unescapeJsonCommandLine, DoesNotMungeSpacesBetweenQuotes) {
  std::vector<std::string> Result = unescapeJsonCommandLine("\\\"  a  b  \\\"");
  ASSERT_EQ(1ul, Result.size());
  EXPECT_EQ("  a  b  ", Result[0]);
}

TEST(unescapeJsonCommandLine, AllowsMultipleQuotedArguments) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "  \\\" a \\\"  \\\" b \\\"  ");
  ASSERT_EQ(2ul, Result.size());
  EXPECT_EQ(" a ", Result[0]);
  EXPECT_EQ(" b ", Result[1]);
}

TEST(unescapeJsonCommandLine, AllowsEmptyArgumentsInQuotes) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "\\\"\\\"\\\"\\\"");
  ASSERT_EQ(1ul, Result.size());
  EXPECT_TRUE(Result[0].empty()) << Result[0];
}

TEST(unescapeJsonCommandLine, ParsesEscapedQuotesInQuotedStrings) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "\\\"\\\\\\\"\\\"");
  ASSERT_EQ(1ul, Result.size());
  EXPECT_EQ("\"", Result[0]);
}

TEST(unescapeJsonCommandLine, ParsesMultipleArgumentsWithEscapedCharacters) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "  \\\\\\\"  \\\"a \\\\\\\" b \\\"     \\\"and\\\\\\\\c\\\"   \\\\\\\"");
  ASSERT_EQ(4ul, Result.size());
  EXPECT_EQ("\"", Result[0]);
  EXPECT_EQ("a \" b ", Result[1]);
  EXPECT_EQ("and\\c", Result[2]);
  EXPECT_EQ("\"", Result[3]);
}

TEST(unescapeJsonCommandLine, ParsesStringsWithoutSpacesIntoSingleArgument) {
  std::vector<std::string> QuotedNoSpaces = unescapeJsonCommandLine(
      "\\\"a\\\"\\\"b\\\"");
  ASSERT_EQ(1ul, QuotedNoSpaces.size());
  EXPECT_EQ("ab", QuotedNoSpaces[0]);

  std::vector<std::string> MixedNoSpaces = unescapeJsonCommandLine(
      "\\\"a\\\"bcd\\\"ef\\\"\\\"\\\"\\\"g\\\"");
  ASSERT_EQ(1ul, MixedNoSpaces.size());
  EXPECT_EQ("abcdefg", MixedNoSpaces[0]);
}

TEST(unescapeJsonCommandLine, ParsesQuotedStringWithoutClosingQuote) {
  std::vector<std::string> Unclosed = unescapeJsonCommandLine("\\\"abc");
  ASSERT_EQ(1ul, Unclosed.size());
  EXPECT_EQ("abc", Unclosed[0]);

  std::vector<std::string> Empty = unescapeJsonCommandLine("\\\"");
  ASSERT_EQ(1ul, Empty.size());
  EXPECT_EQ("", Empty[0]);
}

TEST(unescapeJsonCommandLine, ParsesSingleQuotedString) {
  std::vector<std::string> Args = unescapeJsonCommandLine("a'\\\\b \\\"c\\\"'");
  ASSERT_EQ(1ul, Args.size());
  EXPECT_EQ("a\\b \"c\"", Args[0]);
}

TEST(FixedCompilationDatabase, ReturnsFixedCommandLine) {
  std::vector<std::string> CommandLine;
  CommandLine.push_back("one");
  CommandLine.push_back("two");
  FixedCompilationDatabase Database(".", CommandLine);
  std::vector<CompileCommand> Result =
    Database.getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  std::vector<std::string> ExpectedCommandLine(1, "clang-tool");
  ExpectedCommandLine.insert(ExpectedCommandLine.end(),
                             CommandLine.begin(), CommandLine.end());
  ExpectedCommandLine.push_back("source");
  EXPECT_EQ(".", Result[0].Directory);
  EXPECT_EQ(ExpectedCommandLine, Result[0].CommandLine);
}

TEST(FixedCompilationDatabase, GetAllFiles) {
  std::vector<std::string> CommandLine;
  CommandLine.push_back("one");
  CommandLine.push_back("two");
  FixedCompilationDatabase Database(".", CommandLine);

  EXPECT_EQ(0ul, Database.getAllFiles().size());
}

TEST(FixedCompilationDatabase, GetAllCompileCommands) {
  std::vector<std::string> CommandLine;
  CommandLine.push_back("one");
  CommandLine.push_back("two");
  FixedCompilationDatabase Database(".", CommandLine);

  EXPECT_EQ(0ul, Database.getAllCompileCommands().size());
}

TEST(ParseFixedCompilationDatabase, ReturnsNullOnEmptyArgumentList) {
  int Argc = 0;
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, NULL));
  EXPECT_FALSE(Database);
  EXPECT_EQ(0, Argc);
}

TEST(ParseFixedCompilationDatabase, ReturnsNullWithoutDoubleDash) {
  int Argc = 2;
  const char *Argv[] = { "1", "2" };
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  EXPECT_FALSE(Database);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, ReturnsArgumentsAfterDoubleDash) {
  int Argc = 5;
  const char *Argv[] = {
    "1", "2", "--\0no-constant-folding", "-DDEF3", "-DDEF4"
  };
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE(Database.isValid());
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> CommandLine;
  CommandLine.push_back("clang-tool");
  CommandLine.push_back("-DDEF3");
  CommandLine.push_back("-DDEF4");
  CommandLine.push_back("source");
  ASSERT_EQ(CommandLine, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, ReturnsEmptyCommandLine) {
  int Argc = 3;
  const char *Argv[] = { "1", "2", "--\0no-constant-folding" };
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE(Database.isValid());
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> CommandLine;
  CommandLine.push_back("clang-tool");
  CommandLine.push_back("source");
  ASSERT_EQ(CommandLine, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, HandlesPositionalArgs) {
  const char *Argv[] = {"1", "2", "--", "-c", "somefile.cpp", "-DDEF3"};
  int Argc = sizeof(Argv) / sizeof(char*);
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE(Database.isValid());
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> Expected;
  Expected.push_back("clang-tool");
  Expected.push_back("-c");
  Expected.push_back("-DDEF3");
  Expected.push_back("source");
  ASSERT_EQ(Expected, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, HandlesArgv0) {
  const char *Argv[] = {"1", "2", "--", "mytool", "somefile.cpp"};
  int Argc = sizeof(Argv) / sizeof(char*);
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE(Database.isValid());
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> Expected;
  Expected.push_back("clang-tool");
  Expected.push_back("source");
  ASSERT_EQ(Expected, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

} // end namespace tooling
} // end namespace clang
@


1.1.1.1
log
@Import Clang 3.4rc1 r195771.
@
text
@@


1.1.1.2
log
@Import Clang 3.5svn r201163.
@
text
@d27 1
a27 1
    << "Expected an error because of: " << Explanation.str();
@


1.1.1.2.2.1
log
@Rebase.
@
text
@d45 1
a45 1
  std::unique_ptr<CompilationDatabase> Database(
d56 1
a56 1
  std::unique_ptr<CompilationDatabase> Database(
d118 1
a118 1
  std::unique_ptr<CompilationDatabase> Database(
d436 1
a436 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d445 1
a445 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d456 1
a456 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d458 1
a458 1
  ASSERT_TRUE((bool)Database);
d475 1
a475 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d477 1
a477 1
  ASSERT_TRUE((bool)Database);
d492 1
a492 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d494 1
a494 1
  ASSERT_TRUE((bool)Database);
d511 1
a511 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d513 1
a513 1
  ASSERT_TRUE((bool)Database);
@


1.1.1.3
log
@Import Clang 3.5svn r209886.
@
text
@d45 1
a45 1
  std::unique_ptr<CompilationDatabase> Database(
d56 1
a56 1
  std::unique_ptr<CompilationDatabase> Database(
d118 1
a118 1
  std::unique_ptr<CompilationDatabase> Database(
d436 1
a436 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d445 1
a445 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d456 1
a456 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d458 1
a458 1
  ASSERT_TRUE((bool)Database);
d475 1
a475 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d477 1
a477 1
  ASSERT_TRUE((bool)Database);
d492 1
a492 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d494 1
a494 1
  ASSERT_TRUE((bool)Database);
d511 1
a511 1
  std::unique_ptr<FixedCompilationDatabase> Database(
d513 1
a513 1
  ASSERT_TRUE((bool)Database);
@


1.1.1.4
log
@Import clang 3.6svn r215315.
@
text
@d25 2
a26 2
  EXPECT_EQ(nullptr, JSONCompilationDatabase::loadFromBuffer(JSONDatabase,
                                                             ErrorMessage))
d437 1
a437 1
      FixedCompilationDatabase::loadFromCommandLine(Argc, nullptr));
@


1.1.1.5
log
@Import Clang 3.8.0rc3 r261930.
@
text
@d39 1
a39 1
  expectFailure("[{\"directory\":\"\",\"file\":\"\"}]", "Missing command or arguments");
a40 6
  expectFailure("[{\"directory\":\"\",\"arguments\":[]}]", "Missing file");
  expectFailure("[{\"arguments\":\"\",\"file\":\"\"}]", "Missing directory");
  expectFailure("[{\"directory\":\"\",\"arguments\":\"\",\"file\":\"\"}]", "Arguments not array");
  expectFailure("[{\"directory\":\"\",\"command\":[],\"file\":\"\"}]", "Command not string");
  expectFailure("[{\"directory\":\"\",\"arguments\":[[]],\"file\":\"\"}]",
                "Arguments contain non-string");
d95 2
a96 2
  StringRef FileName2("file2");
  StringRef Command2("command2");
a107 1
  EXPECT_EQ(FileName1, Commands[0].Filename) << ErrorMessage;
a110 1
  EXPECT_EQ(FileName2, Commands[1].Filename) << ErrorMessage;
a112 19

  // Check that order is preserved.
  Commands = getAllCompileCommands(
      ("[{\"directory\":\"" + Directory2 + "\"," +
             "\"command\":\"" + Command2 + "\","
             "\"file\":\"" + FileName2 + "\"},"
       " {\"directory\":\"" + Directory1 + "\"," +
             "\"command\":\"" + Command1 + "\","
             "\"file\":\"" + FileName1 + "\"}]").str(),
      ErrorMessage);
  EXPECT_EQ(2U, Commands.size()) << ErrorMessage;
  EXPECT_EQ(Directory2, Commands[0].Directory) << ErrorMessage;
  EXPECT_EQ(FileName2, Commands[0].Filename) << ErrorMessage;
  ASSERT_EQ(1u, Commands[0].CommandLine.size());
  EXPECT_EQ(Command2, Commands[0].CommandLine[0]) << ErrorMessage;
  EXPECT_EQ(Directory1, Commands[1].Directory) << ErrorMessage;
  EXPECT_EQ(FileName1, Commands[1].Filename) << ErrorMessage;
  ASSERT_EQ(1u, Commands[1].CommandLine.size());
  EXPECT_EQ(Command1, Commands[1].CommandLine[0]) << ErrorMessage;
a128 19
TEST(JSONCompilationDatabase, ArgumentsPreferredOverCommand) {
   StringRef Directory("//net/dir");
   StringRef FileName("//net/dir/filename");
   StringRef Command("command");
   StringRef Arguments = "arguments";
   Twine ArgumentsAccumulate;
   std::string ErrorMessage;
   CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
      FileName,
      ("[{\"directory\":\"" + Directory + "\","
         "\"arguments\":[\"" + Arguments + "\"],"
         "\"command\":\"" + Command + "\","
         "\"file\":\"" + FileName + "\"}]").str(),
      ErrorMessage);
   EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
   EXPECT_EQ(1u, FoundCommand.CommandLine.size()) << ErrorMessage;
   EXPECT_EQ(Arguments, FoundCommand.CommandLine[0]) << ErrorMessage;
}

d130 2
a131 2
  ~FakeComparator() override {}
  bool equivalent(StringRef FileA, StringRef FileB) const override {
a404 1
  StringRef FileName("source");
d406 1
a406 1
    Database.getCompileCommands(FileName);
a412 1
  EXPECT_EQ(FileName, Result[0].Filename);
@


1.1.1.5.2.1
log
@Sync with HEAD
@
text
@d10 1
d25 3
a27 4
  EXPECT_EQ(nullptr,
            JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
                                                    JSONCommandLineSyntax::Gnu))
      << "Expected an error because of: " << Explanation.str();
a46 1
  expectFailure("[{\"output\":[]}]", "Expected strings as value.");
d50 1
a50 2
                                            std::string &ErrorMessage,
                                            JSONCommandLineSyntax Syntax) {
d52 1
a52 2
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
                                              Syntax));
d60 2
a61 3
static std::vector<CompileCommand>
getAllCompileCommands(JSONCommandLineSyntax Syntax, StringRef JSONDatabase,
                      std::string &ErrorMessage) {
d63 1
a63 2
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
                                              Syntax));
d74 1
a74 2
            getAllFiles("[]", ErrorMessage, JSONCommandLineSyntax::Gnu))
      << ErrorMessage;
d82 8
a89 9
  EXPECT_EQ(expected_files,
            getAllFiles("[{\"directory\":\"//net/dir\","
                        "\"command\":\"command\","
                        "\"file\":\"file1\"},"
                        " {\"directory\":\"//net/dir\","
                        "\"command\":\"command\","
                        "\"file\":\"file2\"}]",
                        ErrorMessage, JSONCommandLineSyntax::Gnu))
      << ErrorMessage;
d94 2
a95 4
  EXPECT_EQ(
      0u, getAllCompileCommands(JSONCommandLineSyntax::Gnu, "[]", ErrorMessage)
              .size())
      << ErrorMessage;
a99 1
  StringRef Output1("file1.o");
a102 1
  StringRef Output2("");
d105 6
a110 11
      JSONCommandLineSyntax::Gnu,
      ("[{\"directory\":\"" + Directory1 + "\"," + "\"command\":\"" + Command1 +
       "\","
       "\"file\":\"" +
       FileName1 + "\", \"output\":\"" +
       Output1 + "\"},"
                   " {\"directory\":\"" +
       Directory2 + "\"," + "\"command\":\"" + Command2 + "\","
                                                          "\"file\":\"" +
       FileName2 + "\"}]")
          .str(),
a114 1
  EXPECT_EQ(Output1, Commands[0].Output) << ErrorMessage;
a118 1
  EXPECT_EQ(Output2, Commands[1].Output) << ErrorMessage;
d124 6
a129 10
      JSONCommandLineSyntax::Gnu,
      ("[{\"directory\":\"" + Directory2 + "\"," + "\"command\":\"" + Command2 +
       "\","
       "\"file\":\"" +
       FileName2 + "\"},"
                   " {\"directory\":\"" +
       Directory1 + "\"," + "\"command\":\"" + Command1 + "\","
                                                          "\"file\":\"" +
       FileName1 + "\"}]")
          .str(),
d146 1
a146 2
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
                                              JSONCommandLineSyntax::Gnu));
@


1.1.1.6
log
@Import Clang pre-4.0.0 r291444.
@
text
@d10 1
d25 3
a27 4
  EXPECT_EQ(nullptr,
            JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
                                                    JSONCommandLineSyntax::Gnu))
      << "Expected an error because of: " << Explanation.str();
a46 1
  expectFailure("[{\"output\":[]}]", "Expected strings as value.");
d50 1
a50 2
                                            std::string &ErrorMessage,
                                            JSONCommandLineSyntax Syntax) {
d52 1
a52 2
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
                                              Syntax));
d60 2
a61 3
static std::vector<CompileCommand>
getAllCompileCommands(JSONCommandLineSyntax Syntax, StringRef JSONDatabase,
                      std::string &ErrorMessage) {
d63 1
a63 2
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
                                              Syntax));
d74 1
a74 2
            getAllFiles("[]", ErrorMessage, JSONCommandLineSyntax::Gnu))
      << ErrorMessage;
d82 8
a89 9
  EXPECT_EQ(expected_files,
            getAllFiles("[{\"directory\":\"//net/dir\","
                        "\"command\":\"command\","
                        "\"file\":\"file1\"},"
                        " {\"directory\":\"//net/dir\","
                        "\"command\":\"command\","
                        "\"file\":\"file2\"}]",
                        ErrorMessage, JSONCommandLineSyntax::Gnu))
      << ErrorMessage;
d94 2
a95 4
  EXPECT_EQ(
      0u, getAllCompileCommands(JSONCommandLineSyntax::Gnu, "[]", ErrorMessage)
              .size())
      << ErrorMessage;
a99 1
  StringRef Output1("file1.o");
a102 1
  StringRef Output2("");
d105 6
a110 11
      JSONCommandLineSyntax::Gnu,
      ("[{\"directory\":\"" + Directory1 + "\"," + "\"command\":\"" + Command1 +
       "\","
       "\"file\":\"" +
       FileName1 + "\", \"output\":\"" +
       Output1 + "\"},"
                   " {\"directory\":\"" +
       Directory2 + "\"," + "\"command\":\"" + Command2 + "\","
                                                          "\"file\":\"" +
       FileName2 + "\"}]")
          .str(),
a114 1
  EXPECT_EQ(Output1, Commands[0].Output) << ErrorMessage;
a118 1
  EXPECT_EQ(Output2, Commands[1].Output) << ErrorMessage;
d124 6
a129 10
      JSONCommandLineSyntax::Gnu,
      ("[{\"directory\":\"" + Directory2 + "\"," + "\"command\":\"" + Command2 +
       "\","
       "\"file\":\"" +
       FileName2 + "\"},"
                   " {\"directory\":\"" +
       Directory1 + "\"," + "\"command\":\"" + Command1 + "\","
                                                          "\"file\":\"" +
       FileName1 + "\"}]")
          .str(),
d146 1
a146 2
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
                                              JSONCommandLineSyntax::Gnu));
@


1.1.1.7
log
@Import clang r309604 from branches/release_50
@
text
@d507 2
a508 3
  std::string ErrorMsg;
  std::unique_ptr<FixedCompilationDatabase> Database =
      FixedCompilationDatabase::loadFromCommandLine(Argc, nullptr, ErrorMsg);
a509 1
  EXPECT_TRUE(ErrorMsg.empty());
a515 1
  std::string ErrorMsg;
d517 1
a517 1
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg));
a518 1
  EXPECT_TRUE(ErrorMsg.empty());
a526 1
  std::string ErrorMsg;
d528 1
a528 1
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg));
a529 1
  ASSERT_TRUE(ErrorMsg.empty());
d546 2
a547 3
  std::string ErrorMsg;
  std::unique_ptr<FixedCompilationDatabase> Database =
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg);
a548 1
  ASSERT_TRUE(ErrorMsg.empty());
d563 2
a564 3
  std::string ErrorMsg;
  std::unique_ptr<FixedCompilationDatabase> Database =
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg);
a565 1
  ASSERT_TRUE(ErrorMsg.empty());
a578 21
TEST(ParseFixedCompilationDatabase, HandlesPositionalArgsSyntaxOnly) {
  // Adjust the given command line arguments to ensure that any positional
  // arguments in them are stripped.
  const char *Argv[] = {"--", "somefile.cpp", "-fsyntax-only", "-DDEF3"};
  int Argc = llvm::array_lengthof(Argv);
  std::string ErrorMessage;
  std::unique_ptr<CompilationDatabase> Database =
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMessage);
  ASSERT_TRUE((bool)Database);
  ASSERT_TRUE(ErrorMessage.empty());
  std::vector<CompileCommand> Result = Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> Expected;
  Expected.push_back("clang-tool");
  Expected.push_back("-fsyntax-only");
  Expected.push_back("-DDEF3");
  Expected.push_back("source");
  ASSERT_EQ(Expected, Result[0].CommandLine);
}

d582 2
a583 3
  std::string ErrorMsg;
  std::unique_ptr<FixedCompilationDatabase> Database =
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg);
a584 1
  ASSERT_TRUE(ErrorMsg.empty());
@


1.1.1.7.4.1
log
@Sync with HEAD
@
text
@a628 110
struct MemCDB : public CompilationDatabase {
  using EntryMap = llvm::StringMap<SmallVector<CompileCommand, 1>>;
  EntryMap Entries;
  MemCDB(const EntryMap &E) : Entries(E) {}

  std::vector<CompileCommand> getCompileCommands(StringRef F) const override {
    auto Ret = Entries.lookup(F);
    return {Ret.begin(), Ret.end()};
  }

  std::vector<std::string> getAllFiles() const override {
    std::vector<std::string> Result;
    for (const auto &Entry : Entries)
      Result.push_back(Entry.first());
    return Result;
  }
};

class InterpolateTest : public ::testing::Test {
protected:
  // Adds an entry to the underlying compilation database.
  // A flag is injected: -D <File>, so the command used can be identified.
  void add(llvm::StringRef File, llvm::StringRef Flags = "") {
    llvm::SmallVector<StringRef, 8> Argv = {"clang", File, "-D", File};
    llvm::SplitString(Flags, Argv);
    llvm::SmallString<32> Dir;
    llvm::sys::path::system_temp_directory(false, Dir);
    Entries[path(File)].push_back(
        {Dir, path(File), {Argv.begin(), Argv.end()}, "foo.o"});
  }

  // Turn a unix path fragment (foo/bar.h) into a native path (C:\tmp\foo\bar.h)
  std::string path(llvm::SmallString<32> File) {
    llvm::SmallString<32> Dir;
    llvm::sys::path::system_temp_directory(false, Dir);
    llvm::sys::path::native(File);
    llvm::SmallString<64> Result;
    llvm::sys::path::append(Result, Dir, File);
    return Result.str();
  }

  // Look up the command from a relative path, and return it in string form.
  // The input file is not included in the returned command.
  std::string getCommand(llvm::StringRef F) {
    auto Results =
        inferMissingCompileCommands(llvm::make_unique<MemCDB>(Entries))
            ->getCompileCommands(path(F));
    if (Results.empty())
      return "none";
    // drop the input file argument, so tests don't have to deal with path().
    EXPECT_EQ(Results[0].CommandLine.back(), path(F))
        << "Last arg should be the file";
    Results[0].CommandLine.pop_back();
    return llvm::join(Results[0].CommandLine, " ");
  }

  MemCDB::EntryMap Entries;
};

TEST_F(InterpolateTest, Nearby) {
  add("dir/foo.cpp");
  add("dir/bar.cpp");
  add("an/other/foo.cpp");

  // great: dir and name both match (prefix or full, case insensitive)
  EXPECT_EQ(getCommand("dir/f.cpp"), "clang -D dir/foo.cpp");
  EXPECT_EQ(getCommand("dir/FOO.cpp"), "clang -D dir/foo.cpp");
  // no name match. prefer matching dir, break ties by alpha
  EXPECT_EQ(getCommand("dir/a.cpp"), "clang -D dir/bar.cpp");
  // an exact name match beats one segment of directory match
  EXPECT_EQ(getCommand("some/other/bar.h"),
            "clang -D dir/bar.cpp -x c++-header");
  // two segments of directory match beat a prefix name match
  EXPECT_EQ(getCommand("an/other/b.cpp"), "clang -D an/other/foo.cpp");
  // if nothing matches at all, we still get the closest alpha match
  EXPECT_EQ(getCommand("below/some/obscure/path.cpp"),
            "clang -D an/other/foo.cpp");
}

TEST_F(InterpolateTest, Language) {
  add("dir/foo.cpp", "-std=c++17");
  add("dir/baz.cee", "-x c");

  // .h is ambiguous, so we add explicit language flags
  EXPECT_EQ(getCommand("foo.h"),
            "clang -D dir/foo.cpp -x c++-header -std=c++17");
  // and don't add -x if the inferred language is correct.
  EXPECT_EQ(getCommand("foo.hpp"), "clang -D dir/foo.cpp -std=c++17");
  // respect -x if it's already there.
  EXPECT_EQ(getCommand("baz.h"), "clang -D dir/baz.cee -x c-header");
  // prefer a worse match with the right language
  EXPECT_EQ(getCommand("foo.c"), "clang -D dir/baz.cee");
  Entries.erase(path(StringRef("dir/baz.cee")));
  // Now we transfer across languages, so drop -std too.
  EXPECT_EQ(getCommand("foo.c"), "clang -D dir/foo.cpp");
}

TEST_F(InterpolateTest, Strip) {
  add("dir/foo.cpp", "-o foo.o -Wall");
  // the -o option and the input file are removed, but -Wall is preserved.
  EXPECT_EQ(getCommand("dir/bar.cpp"), "clang -D dir/foo.cpp -Wall");
}

TEST_F(InterpolateTest, Case) {
  add("FOO/BAR/BAZ/SHOUT.cc");
  add("foo/bar/baz/quiet.cc");
  // Case mismatches are completely ignored, so we choose the name match.
  EXPECT_EQ(getCommand("foo/bar/baz/shout.C"), "clang -D FOO/BAR/BAZ/SHOUT.cc");
}

@


1.1.1.7.4.2
log
@Mostly merge changes from HEAD upto 20200411
@
text
@@


1.1.1.7.2.1
log
@Sync with HEAD
@
text
@a628 110
struct MemCDB : public CompilationDatabase {
  using EntryMap = llvm::StringMap<SmallVector<CompileCommand, 1>>;
  EntryMap Entries;
  MemCDB(const EntryMap &E) : Entries(E) {}

  std::vector<CompileCommand> getCompileCommands(StringRef F) const override {
    auto Ret = Entries.lookup(F);
    return {Ret.begin(), Ret.end()};
  }

  std::vector<std::string> getAllFiles() const override {
    std::vector<std::string> Result;
    for (const auto &Entry : Entries)
      Result.push_back(Entry.first());
    return Result;
  }
};

class InterpolateTest : public ::testing::Test {
protected:
  // Adds an entry to the underlying compilation database.
  // A flag is injected: -D <File>, so the command used can be identified.
  void add(llvm::StringRef File, llvm::StringRef Flags = "") {
    llvm::SmallVector<StringRef, 8> Argv = {"clang", File, "-D", File};
    llvm::SplitString(Flags, Argv);
    llvm::SmallString<32> Dir;
    llvm::sys::path::system_temp_directory(false, Dir);
    Entries[path(File)].push_back(
        {Dir, path(File), {Argv.begin(), Argv.end()}, "foo.o"});
  }

  // Turn a unix path fragment (foo/bar.h) into a native path (C:\tmp\foo\bar.h)
  std::string path(llvm::SmallString<32> File) {
    llvm::SmallString<32> Dir;
    llvm::sys::path::system_temp_directory(false, Dir);
    llvm::sys::path::native(File);
    llvm::SmallString<64> Result;
    llvm::sys::path::append(Result, Dir, File);
    return Result.str();
  }

  // Look up the command from a relative path, and return it in string form.
  // The input file is not included in the returned command.
  std::string getCommand(llvm::StringRef F) {
    auto Results =
        inferMissingCompileCommands(llvm::make_unique<MemCDB>(Entries))
            ->getCompileCommands(path(F));
    if (Results.empty())
      return "none";
    // drop the input file argument, so tests don't have to deal with path().
    EXPECT_EQ(Results[0].CommandLine.back(), path(F))
        << "Last arg should be the file";
    Results[0].CommandLine.pop_back();
    return llvm::join(Results[0].CommandLine, " ");
  }

  MemCDB::EntryMap Entries;
};

TEST_F(InterpolateTest, Nearby) {
  add("dir/foo.cpp");
  add("dir/bar.cpp");
  add("an/other/foo.cpp");

  // great: dir and name both match (prefix or full, case insensitive)
  EXPECT_EQ(getCommand("dir/f.cpp"), "clang -D dir/foo.cpp");
  EXPECT_EQ(getCommand("dir/FOO.cpp"), "clang -D dir/foo.cpp");
  // no name match. prefer matching dir, break ties by alpha
  EXPECT_EQ(getCommand("dir/a.cpp"), "clang -D dir/bar.cpp");
  // an exact name match beats one segment of directory match
  EXPECT_EQ(getCommand("some/other/bar.h"),
            "clang -D dir/bar.cpp -x c++-header");
  // two segments of directory match beat a prefix name match
  EXPECT_EQ(getCommand("an/other/b.cpp"), "clang -D an/other/foo.cpp");
  // if nothing matches at all, we still get the closest alpha match
  EXPECT_EQ(getCommand("below/some/obscure/path.cpp"),
            "clang -D an/other/foo.cpp");
}

TEST_F(InterpolateTest, Language) {
  add("dir/foo.cpp", "-std=c++17");
  add("dir/baz.cee", "-x c");

  // .h is ambiguous, so we add explicit language flags
  EXPECT_EQ(getCommand("foo.h"),
            "clang -D dir/foo.cpp -x c++-header -std=c++17");
  // and don't add -x if the inferred language is correct.
  EXPECT_EQ(getCommand("foo.hpp"), "clang -D dir/foo.cpp -std=c++17");
  // respect -x if it's already there.
  EXPECT_EQ(getCommand("baz.h"), "clang -D dir/baz.cee -x c-header");
  // prefer a worse match with the right language
  EXPECT_EQ(getCommand("foo.c"), "clang -D dir/baz.cee");
  Entries.erase(path(StringRef("dir/baz.cee")));
  // Now we transfer across languages, so drop -std too.
  EXPECT_EQ(getCommand("foo.c"), "clang -D dir/foo.cpp");
}

TEST_F(InterpolateTest, Strip) {
  add("dir/foo.cpp", "-o foo.o -Wall");
  // the -o option and the input file are removed, but -Wall is preserved.
  EXPECT_EQ(getCommand("dir/bar.cpp"), "clang -D dir/foo.cpp -Wall");
}

TEST_F(InterpolateTest, Case) {
  add("FOO/BAR/BAZ/SHOUT.cc");
  add("foo/bar/baz/quiet.cc");
  // Case mismatches are completely ignored, so we choose the name match.
  EXPECT_EQ(getCommand("foo/bar/baz/shout.C"), "clang -D FOO/BAR/BAZ/SHOUT.cc");
}

@


1.1.1.8
log
@Import clang r337282 from trunk
@
text
@a628 110
struct MemCDB : public CompilationDatabase {
  using EntryMap = llvm::StringMap<SmallVector<CompileCommand, 1>>;
  EntryMap Entries;
  MemCDB(const EntryMap &E) : Entries(E) {}

  std::vector<CompileCommand> getCompileCommands(StringRef F) const override {
    auto Ret = Entries.lookup(F);
    return {Ret.begin(), Ret.end()};
  }

  std::vector<std::string> getAllFiles() const override {
    std::vector<std::string> Result;
    for (const auto &Entry : Entries)
      Result.push_back(Entry.first());
    return Result;
  }
};

class InterpolateTest : public ::testing::Test {
protected:
  // Adds an entry to the underlying compilation database.
  // A flag is injected: -D <File>, so the command used can be identified.
  void add(llvm::StringRef File, llvm::StringRef Flags = "") {
    llvm::SmallVector<StringRef, 8> Argv = {"clang", File, "-D", File};
    llvm::SplitString(Flags, Argv);
    llvm::SmallString<32> Dir;
    llvm::sys::path::system_temp_directory(false, Dir);
    Entries[path(File)].push_back(
        {Dir, path(File), {Argv.begin(), Argv.end()}, "foo.o"});
  }

  // Turn a unix path fragment (foo/bar.h) into a native path (C:\tmp\foo\bar.h)
  std::string path(llvm::SmallString<32> File) {
    llvm::SmallString<32> Dir;
    llvm::sys::path::system_temp_directory(false, Dir);
    llvm::sys::path::native(File);
    llvm::SmallString<64> Result;
    llvm::sys::path::append(Result, Dir, File);
    return Result.str();
  }

  // Look up the command from a relative path, and return it in string form.
  // The input file is not included in the returned command.
  std::string getCommand(llvm::StringRef F) {
    auto Results =
        inferMissingCompileCommands(llvm::make_unique<MemCDB>(Entries))
            ->getCompileCommands(path(F));
    if (Results.empty())
      return "none";
    // drop the input file argument, so tests don't have to deal with path().
    EXPECT_EQ(Results[0].CommandLine.back(), path(F))
        << "Last arg should be the file";
    Results[0].CommandLine.pop_back();
    return llvm::join(Results[0].CommandLine, " ");
  }

  MemCDB::EntryMap Entries;
};

TEST_F(InterpolateTest, Nearby) {
  add("dir/foo.cpp");
  add("dir/bar.cpp");
  add("an/other/foo.cpp");

  // great: dir and name both match (prefix or full, case insensitive)
  EXPECT_EQ(getCommand("dir/f.cpp"), "clang -D dir/foo.cpp");
  EXPECT_EQ(getCommand("dir/FOO.cpp"), "clang -D dir/foo.cpp");
  // no name match. prefer matching dir, break ties by alpha
  EXPECT_EQ(getCommand("dir/a.cpp"), "clang -D dir/bar.cpp");
  // an exact name match beats one segment of directory match
  EXPECT_EQ(getCommand("some/other/bar.h"),
            "clang -D dir/bar.cpp -x c++-header");
  // two segments of directory match beat a prefix name match
  EXPECT_EQ(getCommand("an/other/b.cpp"), "clang -D an/other/foo.cpp");
  // if nothing matches at all, we still get the closest alpha match
  EXPECT_EQ(getCommand("below/some/obscure/path.cpp"),
            "clang -D an/other/foo.cpp");
}

TEST_F(InterpolateTest, Language) {
  add("dir/foo.cpp", "-std=c++17");
  add("dir/baz.cee", "-x c");

  // .h is ambiguous, so we add explicit language flags
  EXPECT_EQ(getCommand("foo.h"),
            "clang -D dir/foo.cpp -x c++-header -std=c++17");
  // and don't add -x if the inferred language is correct.
  EXPECT_EQ(getCommand("foo.hpp"), "clang -D dir/foo.cpp -std=c++17");
  // respect -x if it's already there.
  EXPECT_EQ(getCommand("baz.h"), "clang -D dir/baz.cee -x c-header");
  // prefer a worse match with the right language
  EXPECT_EQ(getCommand("foo.c"), "clang -D dir/baz.cee");
  Entries.erase(path(StringRef("dir/baz.cee")));
  // Now we transfer across languages, so drop -std too.
  EXPECT_EQ(getCommand("foo.c"), "clang -D dir/foo.cpp");
}

TEST_F(InterpolateTest, Strip) {
  add("dir/foo.cpp", "-o foo.o -Wall");
  // the -o option and the input file are removed, but -Wall is preserved.
  EXPECT_EQ(getCommand("dir/bar.cpp"), "clang -D dir/foo.cpp -Wall");
}

TEST_F(InterpolateTest, Case) {
  add("FOO/BAR/BAZ/SHOUT.cc");
  add("foo/bar/baz/quiet.cc");
  // Case mismatches are completely ignored, so we choose the name match.
  EXPECT_EQ(getCommand("foo/bar/baz/shout.C"), "clang -D FOO/BAR/BAZ/SHOUT.cc");
}

@


1.1.1.9
log
@Mark old LLVM instance as dead.
@
text
@@


1.1.1.4.4.1
log
@file CompilationDatabaseTest.cpp was added on branch tls-maxphys on 2014-08-19 23:49:28 +0000
@
text
@d1 526
@


1.1.1.4.4.2
log
@Rebase to HEAD as of a few days ago.
@
text
@a0 526
//===- unittest/Tooling/CompilationDatabaseTest.cpp -----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/FileMatchTrie.h"
#include "clang/Tooling/JSONCompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/Path.h"
#include "gtest/gtest.h"

namespace clang {
namespace tooling {

static void expectFailure(StringRef JSONDatabase, StringRef Explanation) {
  std::string ErrorMessage;
  EXPECT_EQ(nullptr, JSONCompilationDatabase::loadFromBuffer(JSONDatabase,
                                                             ErrorMessage))
    << "Expected an error because of: " << Explanation.str();
}

TEST(JSONCompilationDatabase, ErrsOnInvalidFormat) {
  expectFailure("", "Empty database");
  expectFailure("{", "Invalid JSON");
  expectFailure("[[]]", "Array instead of object");
  expectFailure("[{\"a\":[]}]", "Array instead of value");
  expectFailure("[{\"a\":\"b\"}]", "Unknown key");
  expectFailure("[{[]:\"\"}]", "Incorrectly typed entry");
  expectFailure("[{}]", "Empty entry");
  expectFailure("[{\"directory\":\"\",\"command\":\"\"}]", "Missing file");
  expectFailure("[{\"directory\":\"\",\"file\":\"\"}]", "Missing command");
  expectFailure("[{\"command\":\"\",\"file\":\"\"}]", "Missing directory");
}

static std::vector<std::string> getAllFiles(StringRef JSONDatabase,
                                            std::string &ErrorMessage) {
  std::unique_ptr<CompilationDatabase> Database(
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
  if (!Database) {
    ADD_FAILURE() << ErrorMessage;
    return std::vector<std::string>();
  }
  return Database->getAllFiles();
}

static std::vector<CompileCommand> getAllCompileCommands(StringRef JSONDatabase,
                                                    std::string &ErrorMessage) {
  std::unique_ptr<CompilationDatabase> Database(
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
  if (!Database) {
    ADD_FAILURE() << ErrorMessage;
    return std::vector<CompileCommand>();
  }
  return Database->getAllCompileCommands();
}

TEST(JSONCompilationDatabase, GetAllFiles) {
  std::string ErrorMessage;
  EXPECT_EQ(std::vector<std::string>(),
            getAllFiles("[]", ErrorMessage)) << ErrorMessage;

  std::vector<std::string> expected_files;
  SmallString<16> PathStorage;
  llvm::sys::path::native("//net/dir/file1", PathStorage);
  expected_files.push_back(PathStorage.str());
  llvm::sys::path::native("//net/dir/file2", PathStorage);
  expected_files.push_back(PathStorage.str());
  EXPECT_EQ(expected_files, getAllFiles(
    "[{\"directory\":\"//net/dir\","
      "\"command\":\"command\","
      "\"file\":\"file1\"},"
    " {\"directory\":\"//net/dir\","
      "\"command\":\"command\","
      "\"file\":\"file2\"}]",
    ErrorMessage)) << ErrorMessage;
}

TEST(JSONCompilationDatabase, GetAllCompileCommands) {
  std::string ErrorMessage;
  EXPECT_EQ(0u,
            getAllCompileCommands("[]", ErrorMessage).size()) << ErrorMessage;

  StringRef Directory1("//net/dir1");
  StringRef FileName1("file1");
  StringRef Command1("command1");
  StringRef Directory2("//net/dir2");
  StringRef FileName2("file1");
  StringRef Command2("command1");

  std::vector<CompileCommand> Commands = getAllCompileCommands(
      ("[{\"directory\":\"" + Directory1 + "\"," +
             "\"command\":\"" + Command1 + "\","
             "\"file\":\"" + FileName1 + "\"},"
       " {\"directory\":\"" + Directory2 + "\"," +
             "\"command\":\"" + Command2 + "\","
             "\"file\":\"" + FileName2 + "\"}]").str(),
      ErrorMessage);
  EXPECT_EQ(2U, Commands.size()) << ErrorMessage;
  EXPECT_EQ(Directory1, Commands[0].Directory) << ErrorMessage;
  ASSERT_EQ(1u, Commands[0].CommandLine.size());
  EXPECT_EQ(Command1, Commands[0].CommandLine[0]) << ErrorMessage;
  EXPECT_EQ(Directory2, Commands[1].Directory) << ErrorMessage;
  ASSERT_EQ(1u, Commands[1].CommandLine.size());
  EXPECT_EQ(Command2, Commands[1].CommandLine[0]) << ErrorMessage;
}

static CompileCommand findCompileArgsInJsonDatabase(StringRef FileName,
                                                    StringRef JSONDatabase,
                                                    std::string &ErrorMessage) {
  std::unique_ptr<CompilationDatabase> Database(
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
  if (!Database)
    return CompileCommand();
  std::vector<CompileCommand> Commands = Database->getCompileCommands(FileName);
  EXPECT_LE(Commands.size(), 1u);
  if (Commands.empty())
    return CompileCommand();
  return Commands[0];
}

struct FakeComparator : public PathComparator {
  virtual ~FakeComparator() {}
  virtual bool equivalent(StringRef FileA, StringRef FileB) const {
    return FileA.equals_lower(FileB);
  }
};

class FileMatchTrieTest : public ::testing::Test {
protected:
  FileMatchTrieTest() : Trie(new FakeComparator()) {}

  StringRef find(StringRef Path) {
    llvm::raw_string_ostream ES(Error);
    return Trie.findEquivalent(Path, ES);
  }

  FileMatchTrie Trie;
  std::string Error;
};

TEST_F(FileMatchTrieTest, InsertingRelativePath) {
  Trie.insert("//net/path/file.cc");
  Trie.insert("file.cc");
  EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
}

TEST_F(FileMatchTrieTest, MatchingRelativePath) {
  EXPECT_EQ("", find("file.cc"));
}

TEST_F(FileMatchTrieTest, ReturnsBestResults) {
  Trie.insert("//net/d/c/b.cc");
  Trie.insert("//net/d/b/b.cc");
  EXPECT_EQ("//net/d/b/b.cc", find("//net/d/b/b.cc"));
}

TEST_F(FileMatchTrieTest, HandlesSymlinks) {
  Trie.insert("//net/AA/file.cc");
  EXPECT_EQ("//net/AA/file.cc", find("//net/aa/file.cc"));
}

TEST_F(FileMatchTrieTest, ReportsSymlinkAmbiguity) {
  Trie.insert("//net/Aa/file.cc");
  Trie.insert("//net/aA/file.cc");
  EXPECT_TRUE(find("//net/aa/file.cc").empty());
  EXPECT_EQ("Path is ambiguous", Error);
}

TEST_F(FileMatchTrieTest, LongerMatchingSuffixPreferred) {
  Trie.insert("//net/src/Aa/file.cc");
  Trie.insert("//net/src/aA/file.cc");
  Trie.insert("//net/SRC/aa/file.cc");
  EXPECT_EQ("//net/SRC/aa/file.cc", find("//net/src/aa/file.cc"));
}

TEST_F(FileMatchTrieTest, EmptyTrie) {
  EXPECT_TRUE(find("//net/some/path").empty());
}

TEST_F(FileMatchTrieTest, NoResult) {
  Trie.insert("//net/somepath/otherfile.cc");
  Trie.insert("//net/otherpath/somefile.cc");
  EXPECT_EQ("", find("//net/somepath/somefile.cc"));
}

TEST_F(FileMatchTrieTest, RootElementDifferent) {
  Trie.insert("//net/path/file.cc");
  Trie.insert("//net/otherpath/file.cc");
  EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
}

TEST_F(FileMatchTrieTest, CannotResolveRelativePath) {
  EXPECT_EQ("", find("relative-path.cc"));
  EXPECT_EQ("Cannot resolve relative paths", Error);
}

TEST(findCompileArgsInJsonDatabase, FindsNothingIfEmpty) {
  std::string ErrorMessage;
  CompileCommand NotFound = findCompileArgsInJsonDatabase(
    "a-file.cpp", "", ErrorMessage);
  EXPECT_TRUE(NotFound.CommandLine.empty()) << ErrorMessage;
  EXPECT_TRUE(NotFound.Directory.empty()) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, ReadsSingleEntry) {
  StringRef Directory("//net/some/directory");
  StringRef FileName("//net/path/to/a-file.cpp");
  StringRef Command("//net/path/to/compiler and some arguments");
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    FileName,
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
  ASSERT_EQ(4u, FoundCommand.CommandLine.size()) << ErrorMessage;
  EXPECT_EQ("//net/path/to/compiler",
            FoundCommand.CommandLine[0]) << ErrorMessage;
  EXPECT_EQ("and", FoundCommand.CommandLine[1]) << ErrorMessage;
  EXPECT_EQ("some", FoundCommand.CommandLine[2]) << ErrorMessage;
  EXPECT_EQ("arguments", FoundCommand.CommandLine[3]) << ErrorMessage;

  CompileCommand NotFound = findCompileArgsInJsonDatabase(
    "a-file.cpp",
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  EXPECT_TRUE(NotFound.Directory.empty()) << ErrorMessage;
  EXPECT_TRUE(NotFound.CommandLine.empty()) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, ReadsCompileCommandLinesWithSpaces) {
  StringRef Directory("//net/some/directory");
  StringRef FileName("//net/path/to/a-file.cpp");
  StringRef Command("\\\"//net/path to compiler\\\" \\\"and an argument\\\"");
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    FileName,
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  ASSERT_EQ(2u, FoundCommand.CommandLine.size());
  EXPECT_EQ("//net/path to compiler",
            FoundCommand.CommandLine[0]) << ErrorMessage;
  EXPECT_EQ("and an argument", FoundCommand.CommandLine[1]) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, ReadsDirectoryWithSpaces) {
  StringRef Directory("//net/some directory / with spaces");
  StringRef FileName("//net/path/to/a-file.cpp");
  StringRef Command("a command");
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    FileName,
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, FindsEntry) {
  StringRef Directory("//net/directory");
  StringRef FileName("file");
  StringRef Command("command");
  std::string JsonDatabase = "[";
  for (int I = 0; I < 10; ++I) {
    if (I > 0) JsonDatabase += ",";
    JsonDatabase +=
      ("{\"directory\":\"" + Directory + Twine(I) + "\"," +
        "\"command\":\"" + Command + Twine(I) + "\","
        "\"file\":\"" + FileName + Twine(I) + "\"}").str();
  }
  JsonDatabase += "]";
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    "//net/directory4/file4", JsonDatabase, ErrorMessage);
  EXPECT_EQ("//net/directory4", FoundCommand.Directory) << ErrorMessage;
  ASSERT_EQ(1u, FoundCommand.CommandLine.size()) << ErrorMessage;
  EXPECT_EQ("command4", FoundCommand.CommandLine[0]) << ErrorMessage;
}

static std::vector<std::string> unescapeJsonCommandLine(StringRef Command) {
  std::string JsonDatabase =
    ("[{\"directory\":\"//net/root\", \"file\":\"test\", \"command\": \"" +
     Command + "\"}]").str();
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    "//net/root/test", JsonDatabase, ErrorMessage);
  EXPECT_TRUE(ErrorMessage.empty()) << ErrorMessage;
  return FoundCommand.CommandLine;
}

TEST(unescapeJsonCommandLine, ReturnsEmptyArrayOnEmptyString) {
  std::vector<std::string> Result = unescapeJsonCommandLine("");
  EXPECT_TRUE(Result.empty());
}

TEST(unescapeJsonCommandLine, SplitsOnSpaces) {
  std::vector<std::string> Result = unescapeJsonCommandLine("a b c");
  ASSERT_EQ(3ul, Result.size());
  EXPECT_EQ("a", Result[0]);
  EXPECT_EQ("b", Result[1]);
  EXPECT_EQ("c", Result[2]);
}

TEST(unescapeJsonCommandLine, MungesMultipleSpaces) {
  std::vector<std::string> Result = unescapeJsonCommandLine("   a   b   ");
  ASSERT_EQ(2ul, Result.size());
  EXPECT_EQ("a", Result[0]);
  EXPECT_EQ("b", Result[1]);
}

TEST(unescapeJsonCommandLine, UnescapesBackslashCharacters) {
  std::vector<std::string> Backslash = unescapeJsonCommandLine("a\\\\\\\\");
  ASSERT_EQ(1ul, Backslash.size());
  EXPECT_EQ("a\\", Backslash[0]);
  std::vector<std::string> Quote = unescapeJsonCommandLine("a\\\\\\\"");
  ASSERT_EQ(1ul, Quote.size());
  EXPECT_EQ("a\"", Quote[0]);
}

TEST(unescapeJsonCommandLine, DoesNotMungeSpacesBetweenQuotes) {
  std::vector<std::string> Result = unescapeJsonCommandLine("\\\"  a  b  \\\"");
  ASSERT_EQ(1ul, Result.size());
  EXPECT_EQ("  a  b  ", Result[0]);
}

TEST(unescapeJsonCommandLine, AllowsMultipleQuotedArguments) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "  \\\" a \\\"  \\\" b \\\"  ");
  ASSERT_EQ(2ul, Result.size());
  EXPECT_EQ(" a ", Result[0]);
  EXPECT_EQ(" b ", Result[1]);
}

TEST(unescapeJsonCommandLine, AllowsEmptyArgumentsInQuotes) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "\\\"\\\"\\\"\\\"");
  ASSERT_EQ(1ul, Result.size());
  EXPECT_TRUE(Result[0].empty()) << Result[0];
}

TEST(unescapeJsonCommandLine, ParsesEscapedQuotesInQuotedStrings) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "\\\"\\\\\\\"\\\"");
  ASSERT_EQ(1ul, Result.size());
  EXPECT_EQ("\"", Result[0]);
}

TEST(unescapeJsonCommandLine, ParsesMultipleArgumentsWithEscapedCharacters) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "  \\\\\\\"  \\\"a \\\\\\\" b \\\"     \\\"and\\\\\\\\c\\\"   \\\\\\\"");
  ASSERT_EQ(4ul, Result.size());
  EXPECT_EQ("\"", Result[0]);
  EXPECT_EQ("a \" b ", Result[1]);
  EXPECT_EQ("and\\c", Result[2]);
  EXPECT_EQ("\"", Result[3]);
}

TEST(unescapeJsonCommandLine, ParsesStringsWithoutSpacesIntoSingleArgument) {
  std::vector<std::string> QuotedNoSpaces = unescapeJsonCommandLine(
      "\\\"a\\\"\\\"b\\\"");
  ASSERT_EQ(1ul, QuotedNoSpaces.size());
  EXPECT_EQ("ab", QuotedNoSpaces[0]);

  std::vector<std::string> MixedNoSpaces = unescapeJsonCommandLine(
      "\\\"a\\\"bcd\\\"ef\\\"\\\"\\\"\\\"g\\\"");
  ASSERT_EQ(1ul, MixedNoSpaces.size());
  EXPECT_EQ("abcdefg", MixedNoSpaces[0]);
}

TEST(unescapeJsonCommandLine, ParsesQuotedStringWithoutClosingQuote) {
  std::vector<std::string> Unclosed = unescapeJsonCommandLine("\\\"abc");
  ASSERT_EQ(1ul, Unclosed.size());
  EXPECT_EQ("abc", Unclosed[0]);

  std::vector<std::string> Empty = unescapeJsonCommandLine("\\\"");
  ASSERT_EQ(1ul, Empty.size());
  EXPECT_EQ("", Empty[0]);
}

TEST(unescapeJsonCommandLine, ParsesSingleQuotedString) {
  std::vector<std::string> Args = unescapeJsonCommandLine("a'\\\\b \\\"c\\\"'");
  ASSERT_EQ(1ul, Args.size());
  EXPECT_EQ("a\\b \"c\"", Args[0]);
}

TEST(FixedCompilationDatabase, ReturnsFixedCommandLine) {
  std::vector<std::string> CommandLine;
  CommandLine.push_back("one");
  CommandLine.push_back("two");
  FixedCompilationDatabase Database(".", CommandLine);
  std::vector<CompileCommand> Result =
    Database.getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  std::vector<std::string> ExpectedCommandLine(1, "clang-tool");
  ExpectedCommandLine.insert(ExpectedCommandLine.end(),
                             CommandLine.begin(), CommandLine.end());
  ExpectedCommandLine.push_back("source");
  EXPECT_EQ(".", Result[0].Directory);
  EXPECT_EQ(ExpectedCommandLine, Result[0].CommandLine);
}

TEST(FixedCompilationDatabase, GetAllFiles) {
  std::vector<std::string> CommandLine;
  CommandLine.push_back("one");
  CommandLine.push_back("two");
  FixedCompilationDatabase Database(".", CommandLine);

  EXPECT_EQ(0ul, Database.getAllFiles().size());
}

TEST(FixedCompilationDatabase, GetAllCompileCommands) {
  std::vector<std::string> CommandLine;
  CommandLine.push_back("one");
  CommandLine.push_back("two");
  FixedCompilationDatabase Database(".", CommandLine);

  EXPECT_EQ(0ul, Database.getAllCompileCommands().size());
}

TEST(ParseFixedCompilationDatabase, ReturnsNullOnEmptyArgumentList) {
  int Argc = 0;
  std::unique_ptr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, nullptr));
  EXPECT_FALSE(Database);
  EXPECT_EQ(0, Argc);
}

TEST(ParseFixedCompilationDatabase, ReturnsNullWithoutDoubleDash) {
  int Argc = 2;
  const char *Argv[] = { "1", "2" };
  std::unique_ptr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  EXPECT_FALSE(Database);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, ReturnsArgumentsAfterDoubleDash) {
  int Argc = 5;
  const char *Argv[] = {
    "1", "2", "--\0no-constant-folding", "-DDEF3", "-DDEF4"
  };
  std::unique_ptr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE((bool)Database);
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> CommandLine;
  CommandLine.push_back("clang-tool");
  CommandLine.push_back("-DDEF3");
  CommandLine.push_back("-DDEF4");
  CommandLine.push_back("source");
  ASSERT_EQ(CommandLine, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, ReturnsEmptyCommandLine) {
  int Argc = 3;
  const char *Argv[] = { "1", "2", "--\0no-constant-folding" };
  std::unique_ptr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE((bool)Database);
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> CommandLine;
  CommandLine.push_back("clang-tool");
  CommandLine.push_back("source");
  ASSERT_EQ(CommandLine, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, HandlesPositionalArgs) {
  const char *Argv[] = {"1", "2", "--", "-c", "somefile.cpp", "-DDEF3"};
  int Argc = sizeof(Argv) / sizeof(char*);
  std::unique_ptr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE((bool)Database);
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> Expected;
  Expected.push_back("clang-tool");
  Expected.push_back("-c");
  Expected.push_back("-DDEF3");
  Expected.push_back("source");
  ASSERT_EQ(Expected, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, HandlesArgv0) {
  const char *Argv[] = {"1", "2", "--", "mytool", "somefile.cpp"};
  int Argc = sizeof(Argv) / sizeof(char*);
  std::unique_ptr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE((bool)Database);
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> Expected;
  Expected.push_back("clang-tool");
  Expected.push_back("source");
  ASSERT_EQ(Expected, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

} // end namespace tooling
} // end namespace clang
@


1.1.1.2.4.1
log
@file CompilationDatabaseTest.cpp was added on branch yamt-pagecache on 2014-05-22 16:19:49 +0000
@
text
@d1 526
@


1.1.1.2.4.2
log
@sync with head.

for a reference, the tree before this commit was tagged
as yamt-pagecache-tag8.

this commit was splitted into small chunks to avoid
a limitation of cvs.  ("Protocol error: too many arguments")
@
text
@a0 526
//===- unittest/Tooling/CompilationDatabaseTest.cpp -----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/FileMatchTrie.h"
#include "clang/Tooling/JSONCompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/Path.h"
#include "gtest/gtest.h"

namespace clang {
namespace tooling {

static void expectFailure(StringRef JSONDatabase, StringRef Explanation) {
  std::string ErrorMessage;
  EXPECT_EQ(NULL, JSONCompilationDatabase::loadFromBuffer(JSONDatabase,
                                                          ErrorMessage))
    << "Expected an error because of: " << Explanation.str();
}

TEST(JSONCompilationDatabase, ErrsOnInvalidFormat) {
  expectFailure("", "Empty database");
  expectFailure("{", "Invalid JSON");
  expectFailure("[[]]", "Array instead of object");
  expectFailure("[{\"a\":[]}]", "Array instead of value");
  expectFailure("[{\"a\":\"b\"}]", "Unknown key");
  expectFailure("[{[]:\"\"}]", "Incorrectly typed entry");
  expectFailure("[{}]", "Empty entry");
  expectFailure("[{\"directory\":\"\",\"command\":\"\"}]", "Missing file");
  expectFailure("[{\"directory\":\"\",\"file\":\"\"}]", "Missing command");
  expectFailure("[{\"command\":\"\",\"file\":\"\"}]", "Missing directory");
}

static std::vector<std::string> getAllFiles(StringRef JSONDatabase,
                                            std::string &ErrorMessage) {
  OwningPtr<CompilationDatabase> Database(
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
  if (!Database) {
    ADD_FAILURE() << ErrorMessage;
    return std::vector<std::string>();
  }
  return Database->getAllFiles();
}

static std::vector<CompileCommand> getAllCompileCommands(StringRef JSONDatabase,
                                                    std::string &ErrorMessage) {
  OwningPtr<CompilationDatabase> Database(
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
  if (!Database) {
    ADD_FAILURE() << ErrorMessage;
    return std::vector<CompileCommand>();
  }
  return Database->getAllCompileCommands();
}

TEST(JSONCompilationDatabase, GetAllFiles) {
  std::string ErrorMessage;
  EXPECT_EQ(std::vector<std::string>(),
            getAllFiles("[]", ErrorMessage)) << ErrorMessage;

  std::vector<std::string> expected_files;
  SmallString<16> PathStorage;
  llvm::sys::path::native("//net/dir/file1", PathStorage);
  expected_files.push_back(PathStorage.str());
  llvm::sys::path::native("//net/dir/file2", PathStorage);
  expected_files.push_back(PathStorage.str());
  EXPECT_EQ(expected_files, getAllFiles(
    "[{\"directory\":\"//net/dir\","
      "\"command\":\"command\","
      "\"file\":\"file1\"},"
    " {\"directory\":\"//net/dir\","
      "\"command\":\"command\","
      "\"file\":\"file2\"}]",
    ErrorMessage)) << ErrorMessage;
}

TEST(JSONCompilationDatabase, GetAllCompileCommands) {
  std::string ErrorMessage;
  EXPECT_EQ(0u,
            getAllCompileCommands("[]", ErrorMessage).size()) << ErrorMessage;

  StringRef Directory1("//net/dir1");
  StringRef FileName1("file1");
  StringRef Command1("command1");
  StringRef Directory2("//net/dir2");
  StringRef FileName2("file1");
  StringRef Command2("command1");

  std::vector<CompileCommand> Commands = getAllCompileCommands(
      ("[{\"directory\":\"" + Directory1 + "\"," +
             "\"command\":\"" + Command1 + "\","
             "\"file\":\"" + FileName1 + "\"},"
       " {\"directory\":\"" + Directory2 + "\"," +
             "\"command\":\"" + Command2 + "\","
             "\"file\":\"" + FileName2 + "\"}]").str(),
      ErrorMessage);
  EXPECT_EQ(2U, Commands.size()) << ErrorMessage;
  EXPECT_EQ(Directory1, Commands[0].Directory) << ErrorMessage;
  ASSERT_EQ(1u, Commands[0].CommandLine.size());
  EXPECT_EQ(Command1, Commands[0].CommandLine[0]) << ErrorMessage;
  EXPECT_EQ(Directory2, Commands[1].Directory) << ErrorMessage;
  ASSERT_EQ(1u, Commands[1].CommandLine.size());
  EXPECT_EQ(Command2, Commands[1].CommandLine[0]) << ErrorMessage;
}

static CompileCommand findCompileArgsInJsonDatabase(StringRef FileName,
                                                    StringRef JSONDatabase,
                                                    std::string &ErrorMessage) {
  OwningPtr<CompilationDatabase> Database(
      JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
  if (!Database)
    return CompileCommand();
  std::vector<CompileCommand> Commands = Database->getCompileCommands(FileName);
  EXPECT_LE(Commands.size(), 1u);
  if (Commands.empty())
    return CompileCommand();
  return Commands[0];
}

struct FakeComparator : public PathComparator {
  virtual ~FakeComparator() {}
  virtual bool equivalent(StringRef FileA, StringRef FileB) const {
    return FileA.equals_lower(FileB);
  }
};

class FileMatchTrieTest : public ::testing::Test {
protected:
  FileMatchTrieTest() : Trie(new FakeComparator()) {}

  StringRef find(StringRef Path) {
    llvm::raw_string_ostream ES(Error);
    return Trie.findEquivalent(Path, ES);
  }

  FileMatchTrie Trie;
  std::string Error;
};

TEST_F(FileMatchTrieTest, InsertingRelativePath) {
  Trie.insert("//net/path/file.cc");
  Trie.insert("file.cc");
  EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
}

TEST_F(FileMatchTrieTest, MatchingRelativePath) {
  EXPECT_EQ("", find("file.cc"));
}

TEST_F(FileMatchTrieTest, ReturnsBestResults) {
  Trie.insert("//net/d/c/b.cc");
  Trie.insert("//net/d/b/b.cc");
  EXPECT_EQ("//net/d/b/b.cc", find("//net/d/b/b.cc"));
}

TEST_F(FileMatchTrieTest, HandlesSymlinks) {
  Trie.insert("//net/AA/file.cc");
  EXPECT_EQ("//net/AA/file.cc", find("//net/aa/file.cc"));
}

TEST_F(FileMatchTrieTest, ReportsSymlinkAmbiguity) {
  Trie.insert("//net/Aa/file.cc");
  Trie.insert("//net/aA/file.cc");
  EXPECT_TRUE(find("//net/aa/file.cc").empty());
  EXPECT_EQ("Path is ambiguous", Error);
}

TEST_F(FileMatchTrieTest, LongerMatchingSuffixPreferred) {
  Trie.insert("//net/src/Aa/file.cc");
  Trie.insert("//net/src/aA/file.cc");
  Trie.insert("//net/SRC/aa/file.cc");
  EXPECT_EQ("//net/SRC/aa/file.cc", find("//net/src/aa/file.cc"));
}

TEST_F(FileMatchTrieTest, EmptyTrie) {
  EXPECT_TRUE(find("//net/some/path").empty());
}

TEST_F(FileMatchTrieTest, NoResult) {
  Trie.insert("//net/somepath/otherfile.cc");
  Trie.insert("//net/otherpath/somefile.cc");
  EXPECT_EQ("", find("//net/somepath/somefile.cc"));
}

TEST_F(FileMatchTrieTest, RootElementDifferent) {
  Trie.insert("//net/path/file.cc");
  Trie.insert("//net/otherpath/file.cc");
  EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
}

TEST_F(FileMatchTrieTest, CannotResolveRelativePath) {
  EXPECT_EQ("", find("relative-path.cc"));
  EXPECT_EQ("Cannot resolve relative paths", Error);
}

TEST(findCompileArgsInJsonDatabase, FindsNothingIfEmpty) {
  std::string ErrorMessage;
  CompileCommand NotFound = findCompileArgsInJsonDatabase(
    "a-file.cpp", "", ErrorMessage);
  EXPECT_TRUE(NotFound.CommandLine.empty()) << ErrorMessage;
  EXPECT_TRUE(NotFound.Directory.empty()) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, ReadsSingleEntry) {
  StringRef Directory("//net/some/directory");
  StringRef FileName("//net/path/to/a-file.cpp");
  StringRef Command("//net/path/to/compiler and some arguments");
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    FileName,
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
  ASSERT_EQ(4u, FoundCommand.CommandLine.size()) << ErrorMessage;
  EXPECT_EQ("//net/path/to/compiler",
            FoundCommand.CommandLine[0]) << ErrorMessage;
  EXPECT_EQ("and", FoundCommand.CommandLine[1]) << ErrorMessage;
  EXPECT_EQ("some", FoundCommand.CommandLine[2]) << ErrorMessage;
  EXPECT_EQ("arguments", FoundCommand.CommandLine[3]) << ErrorMessage;

  CompileCommand NotFound = findCompileArgsInJsonDatabase(
    "a-file.cpp",
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  EXPECT_TRUE(NotFound.Directory.empty()) << ErrorMessage;
  EXPECT_TRUE(NotFound.CommandLine.empty()) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, ReadsCompileCommandLinesWithSpaces) {
  StringRef Directory("//net/some/directory");
  StringRef FileName("//net/path/to/a-file.cpp");
  StringRef Command("\\\"//net/path to compiler\\\" \\\"and an argument\\\"");
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    FileName,
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  ASSERT_EQ(2u, FoundCommand.CommandLine.size());
  EXPECT_EQ("//net/path to compiler",
            FoundCommand.CommandLine[0]) << ErrorMessage;
  EXPECT_EQ("and an argument", FoundCommand.CommandLine[1]) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, ReadsDirectoryWithSpaces) {
  StringRef Directory("//net/some directory / with spaces");
  StringRef FileName("//net/path/to/a-file.cpp");
  StringRef Command("a command");
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    FileName,
    ("[{\"directory\":\"" + Directory + "\"," +
       "\"command\":\"" + Command + "\","
       "\"file\":\"" + FileName + "\"}]").str(),
    ErrorMessage);
  EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
}

TEST(findCompileArgsInJsonDatabase, FindsEntry) {
  StringRef Directory("//net/directory");
  StringRef FileName("file");
  StringRef Command("command");
  std::string JsonDatabase = "[";
  for (int I = 0; I < 10; ++I) {
    if (I > 0) JsonDatabase += ",";
    JsonDatabase +=
      ("{\"directory\":\"" + Directory + Twine(I) + "\"," +
        "\"command\":\"" + Command + Twine(I) + "\","
        "\"file\":\"" + FileName + Twine(I) + "\"}").str();
  }
  JsonDatabase += "]";
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    "//net/directory4/file4", JsonDatabase, ErrorMessage);
  EXPECT_EQ("//net/directory4", FoundCommand.Directory) << ErrorMessage;
  ASSERT_EQ(1u, FoundCommand.CommandLine.size()) << ErrorMessage;
  EXPECT_EQ("command4", FoundCommand.CommandLine[0]) << ErrorMessage;
}

static std::vector<std::string> unescapeJsonCommandLine(StringRef Command) {
  std::string JsonDatabase =
    ("[{\"directory\":\"//net/root\", \"file\":\"test\", \"command\": \"" +
     Command + "\"}]").str();
  std::string ErrorMessage;
  CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
    "//net/root/test", JsonDatabase, ErrorMessage);
  EXPECT_TRUE(ErrorMessage.empty()) << ErrorMessage;
  return FoundCommand.CommandLine;
}

TEST(unescapeJsonCommandLine, ReturnsEmptyArrayOnEmptyString) {
  std::vector<std::string> Result = unescapeJsonCommandLine("");
  EXPECT_TRUE(Result.empty());
}

TEST(unescapeJsonCommandLine, SplitsOnSpaces) {
  std::vector<std::string> Result = unescapeJsonCommandLine("a b c");
  ASSERT_EQ(3ul, Result.size());
  EXPECT_EQ("a", Result[0]);
  EXPECT_EQ("b", Result[1]);
  EXPECT_EQ("c", Result[2]);
}

TEST(unescapeJsonCommandLine, MungesMultipleSpaces) {
  std::vector<std::string> Result = unescapeJsonCommandLine("   a   b   ");
  ASSERT_EQ(2ul, Result.size());
  EXPECT_EQ("a", Result[0]);
  EXPECT_EQ("b", Result[1]);
}

TEST(unescapeJsonCommandLine, UnescapesBackslashCharacters) {
  std::vector<std::string> Backslash = unescapeJsonCommandLine("a\\\\\\\\");
  ASSERT_EQ(1ul, Backslash.size());
  EXPECT_EQ("a\\", Backslash[0]);
  std::vector<std::string> Quote = unescapeJsonCommandLine("a\\\\\\\"");
  ASSERT_EQ(1ul, Quote.size());
  EXPECT_EQ("a\"", Quote[0]);
}

TEST(unescapeJsonCommandLine, DoesNotMungeSpacesBetweenQuotes) {
  std::vector<std::string> Result = unescapeJsonCommandLine("\\\"  a  b  \\\"");
  ASSERT_EQ(1ul, Result.size());
  EXPECT_EQ("  a  b  ", Result[0]);
}

TEST(unescapeJsonCommandLine, AllowsMultipleQuotedArguments) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "  \\\" a \\\"  \\\" b \\\"  ");
  ASSERT_EQ(2ul, Result.size());
  EXPECT_EQ(" a ", Result[0]);
  EXPECT_EQ(" b ", Result[1]);
}

TEST(unescapeJsonCommandLine, AllowsEmptyArgumentsInQuotes) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "\\\"\\\"\\\"\\\"");
  ASSERT_EQ(1ul, Result.size());
  EXPECT_TRUE(Result[0].empty()) << Result[0];
}

TEST(unescapeJsonCommandLine, ParsesEscapedQuotesInQuotedStrings) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "\\\"\\\\\\\"\\\"");
  ASSERT_EQ(1ul, Result.size());
  EXPECT_EQ("\"", Result[0]);
}

TEST(unescapeJsonCommandLine, ParsesMultipleArgumentsWithEscapedCharacters) {
  std::vector<std::string> Result = unescapeJsonCommandLine(
      "  \\\\\\\"  \\\"a \\\\\\\" b \\\"     \\\"and\\\\\\\\c\\\"   \\\\\\\"");
  ASSERT_EQ(4ul, Result.size());
  EXPECT_EQ("\"", Result[0]);
  EXPECT_EQ("a \" b ", Result[1]);
  EXPECT_EQ("and\\c", Result[2]);
  EXPECT_EQ("\"", Result[3]);
}

TEST(unescapeJsonCommandLine, ParsesStringsWithoutSpacesIntoSingleArgument) {
  std::vector<std::string> QuotedNoSpaces = unescapeJsonCommandLine(
      "\\\"a\\\"\\\"b\\\"");
  ASSERT_EQ(1ul, QuotedNoSpaces.size());
  EXPECT_EQ("ab", QuotedNoSpaces[0]);

  std::vector<std::string> MixedNoSpaces = unescapeJsonCommandLine(
      "\\\"a\\\"bcd\\\"ef\\\"\\\"\\\"\\\"g\\\"");
  ASSERT_EQ(1ul, MixedNoSpaces.size());
  EXPECT_EQ("abcdefg", MixedNoSpaces[0]);
}

TEST(unescapeJsonCommandLine, ParsesQuotedStringWithoutClosingQuote) {
  std::vector<std::string> Unclosed = unescapeJsonCommandLine("\\\"abc");
  ASSERT_EQ(1ul, Unclosed.size());
  EXPECT_EQ("abc", Unclosed[0]);

  std::vector<std::string> Empty = unescapeJsonCommandLine("\\\"");
  ASSERT_EQ(1ul, Empty.size());
  EXPECT_EQ("", Empty[0]);
}

TEST(unescapeJsonCommandLine, ParsesSingleQuotedString) {
  std::vector<std::string> Args = unescapeJsonCommandLine("a'\\\\b \\\"c\\\"'");
  ASSERT_EQ(1ul, Args.size());
  EXPECT_EQ("a\\b \"c\"", Args[0]);
}

TEST(FixedCompilationDatabase, ReturnsFixedCommandLine) {
  std::vector<std::string> CommandLine;
  CommandLine.push_back("one");
  CommandLine.push_back("two");
  FixedCompilationDatabase Database(".", CommandLine);
  std::vector<CompileCommand> Result =
    Database.getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  std::vector<std::string> ExpectedCommandLine(1, "clang-tool");
  ExpectedCommandLine.insert(ExpectedCommandLine.end(),
                             CommandLine.begin(), CommandLine.end());
  ExpectedCommandLine.push_back("source");
  EXPECT_EQ(".", Result[0].Directory);
  EXPECT_EQ(ExpectedCommandLine, Result[0].CommandLine);
}

TEST(FixedCompilationDatabase, GetAllFiles) {
  std::vector<std::string> CommandLine;
  CommandLine.push_back("one");
  CommandLine.push_back("two");
  FixedCompilationDatabase Database(".", CommandLine);

  EXPECT_EQ(0ul, Database.getAllFiles().size());
}

TEST(FixedCompilationDatabase, GetAllCompileCommands) {
  std::vector<std::string> CommandLine;
  CommandLine.push_back("one");
  CommandLine.push_back("two");
  FixedCompilationDatabase Database(".", CommandLine);

  EXPECT_EQ(0ul, Database.getAllCompileCommands().size());
}

TEST(ParseFixedCompilationDatabase, ReturnsNullOnEmptyArgumentList) {
  int Argc = 0;
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, NULL));
  EXPECT_FALSE(Database);
  EXPECT_EQ(0, Argc);
}

TEST(ParseFixedCompilationDatabase, ReturnsNullWithoutDoubleDash) {
  int Argc = 2;
  const char *Argv[] = { "1", "2" };
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  EXPECT_FALSE(Database);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, ReturnsArgumentsAfterDoubleDash) {
  int Argc = 5;
  const char *Argv[] = {
    "1", "2", "--\0no-constant-folding", "-DDEF3", "-DDEF4"
  };
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE(Database.isValid());
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> CommandLine;
  CommandLine.push_back("clang-tool");
  CommandLine.push_back("-DDEF3");
  CommandLine.push_back("-DDEF4");
  CommandLine.push_back("source");
  ASSERT_EQ(CommandLine, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, ReturnsEmptyCommandLine) {
  int Argc = 3;
  const char *Argv[] = { "1", "2", "--\0no-constant-folding" };
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE(Database.isValid());
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> CommandLine;
  CommandLine.push_back("clang-tool");
  CommandLine.push_back("source");
  ASSERT_EQ(CommandLine, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, HandlesPositionalArgs) {
  const char *Argv[] = {"1", "2", "--", "-c", "somefile.cpp", "-DDEF3"};
  int Argc = sizeof(Argv) / sizeof(char*);
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE(Database.isValid());
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> Expected;
  Expected.push_back("clang-tool");
  Expected.push_back("-c");
  Expected.push_back("-DDEF3");
  Expected.push_back("source");
  ASSERT_EQ(Expected, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

TEST(ParseFixedCompilationDatabase, HandlesArgv0) {
  const char *Argv[] = {"1", "2", "--", "mytool", "somefile.cpp"};
  int Argc = sizeof(Argv) / sizeof(char*);
  OwningPtr<FixedCompilationDatabase> Database(
      FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
  ASSERT_TRUE(Database.isValid());
  std::vector<CompileCommand> Result =
    Database->getCompileCommands("source");
  ASSERT_EQ(1ul, Result.size());
  ASSERT_EQ(".", Result[0].Directory);
  std::vector<std::string> Expected;
  Expected.push_back("clang-tool");
  Expected.push_back("source");
  ASSERT_EQ(Expected, Result[0].CommandLine);
  EXPECT_EQ(2, Argc);
}

} // end namespace tooling
} // end namespace clang
@


