SymbolCollectorTests.cpp 48.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
//===-- SymbolCollectorTests.cpp  -------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "Annotations.h"
#include "TestFS.h"
#include "TestTU.h"
#include "index/SymbolCollector.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Index/IndexingAction.h"
#include "clang/Index/IndexingOptions.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "gmock/gmock-matchers.h"
#include "gmock/gmock-more-matchers.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include <memory>
#include <string>

namespace clang {
namespace clangd {
namespace {

using ::testing::_;
using ::testing::AllOf;
using ::testing::Contains;
using ::testing::Each;
using ::testing::ElementsAre;
using ::testing::Field;
using ::testing::IsEmpty;
using ::testing::Not;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;
using ::testing::UnorderedElementsAreArray;

// GMock helpers for matching Symbol.
MATCHER_P(Labeled, Label, "") {
  return (arg.Name + arg.Signature).str() == Label;
}
MATCHER_P(ReturnType, D, "") { return arg.ReturnType == D; }
MATCHER_P(Doc, D, "") { return arg.Documentation == D; }
MATCHER_P(Snippet, S, "") {
  return (arg.Name + arg.CompletionSnippetSuffix).str() == S;
}
MATCHER_P(QName, Name, "") { return (arg.Scope + arg.Name).str() == Name; }
MATCHER_P(TemplateArgs, TemplArgs, "") {
  return arg.TemplateSpecializationArgs == TemplArgs;
}
MATCHER_P(DeclURI, P, "") {
  return StringRef(arg.CanonicalDeclaration.FileURI) == P;
}
MATCHER_P(DefURI, P, "") { return StringRef(arg.Definition.FileURI) == P; }
MATCHER(IncludeHeader, "") { return !arg.IncludeHeaders.empty(); }
MATCHER_P(IncludeHeader, P, "") {
  return (arg.IncludeHeaders.size() == 1) &&
         (arg.IncludeHeaders.begin()->IncludeHeader == P);
}
MATCHER_P2(IncludeHeaderWithRef, IncludeHeader, References, "") {
  return (arg.IncludeHeader == IncludeHeader) && (arg.References == References);
}
MATCHER_P(DeclRange, Pos, "") {
  return std::make_tuple(arg.CanonicalDeclaration.Start.line(),
                         arg.CanonicalDeclaration.Start.column(),
                         arg.CanonicalDeclaration.End.line(),
                         arg.CanonicalDeclaration.End.column()) ==
         std::make_tuple(Pos.start.line, Pos.start.character, Pos.end.line,
                         Pos.end.character);
}
MATCHER_P(DefRange, Pos, "") {
  return std::make_tuple(
             arg.Definition.Start.line(), arg.Definition.Start.column(),
             arg.Definition.End.line(), arg.Definition.End.column()) ==
         std::make_tuple(Pos.start.line, Pos.start.character, Pos.end.line,
                         Pos.end.character);
}
MATCHER_P(RefCount, R, "") { return int(arg.References) == R; }
MATCHER_P(ForCodeCompletion, IsIndexedForCodeCompletion, "") {
  return static_cast<bool>(arg.Flags & Symbol::IndexedForCodeCompletion) ==
         IsIndexedForCodeCompletion;
}
MATCHER(Deprecated, "") { return arg.Flags & Symbol::Deprecated; }
MATCHER(ImplementationDetail, "") {
  return arg.Flags & Symbol::ImplementationDetail;
}
MATCHER(VisibleOutsideFile, "") {
  return static_cast<bool>(arg.Flags & Symbol::VisibleOutsideFile);
}
MATCHER(RefRange, "") {
  const Ref &Pos = ::testing::get<0>(arg);
  const Range &Range = ::testing::get<1>(arg);
  return std::make_tuple(Pos.Location.Start.line(), Pos.Location.Start.column(),
                         Pos.Location.End.line(), Pos.Location.End.column()) ==
         std::make_tuple(Range.start.line, Range.start.character,
                         Range.end.line, Range.end.character);
}
::testing::Matcher<const std::vector<Ref> &>
HaveRanges(const std::vector<Range> Ranges) {
  return ::testing::UnorderedPointwise(RefRange(), Ranges);
}

class ShouldCollectSymbolTest : public ::testing::Test {
public:
  void build(llvm::StringRef HeaderCode, llvm::StringRef Code = "") {
    File.HeaderFilename = HeaderName;
    File.Filename = FileName;
    File.HeaderCode = HeaderCode;
    File.Code = Code;
    AST = File.build();
  }

  // build() must have been called.
  bool shouldCollect(llvm::StringRef Name, bool Qualified = true) {
    assert(AST.hasValue());
    const NamedDecl &ND =
        Qualified ? findDecl(*AST, Name) : findUnqualifiedDecl(*AST, Name);
    const SourceManager &SM = AST->getSourceManager();
    bool MainFile = isInsideMainFile(ND.getBeginLoc(), SM);
    return SymbolCollector::shouldCollectSymbol(
        ND, AST->getASTContext(), SymbolCollector::Options(), MainFile);
  }

protected:
  std::string HeaderName = "f.h";
  std::string FileName = "f.cpp";
  TestTU File;
  llvm::Optional<ParsedAST> AST; // Initialized after build.
};

TEST_F(ShouldCollectSymbolTest, ShouldCollectSymbol) {
  build(R"(
    namespace nx {
    class X{};
    auto f() { int Local; } // auto ensures function body is parsed.
    struct { int x; } var;
    }
  )",
        R"(
    class InMain {};
    namespace { class InAnonymous {}; }
    static void g();
  )");
  auto AST = File.build();
  EXPECT_TRUE(shouldCollect("nx"));
  EXPECT_TRUE(shouldCollect("nx::X"));
  EXPECT_TRUE(shouldCollect("nx::f"));
  EXPECT_TRUE(shouldCollect("InMain"));
  EXPECT_TRUE(shouldCollect("InAnonymous", /*Qualified=*/false));
  EXPECT_TRUE(shouldCollect("g"));

  EXPECT_FALSE(shouldCollect("Local", /*Qualified=*/false));
}

TEST_F(ShouldCollectSymbolTest, NoPrivateProtoSymbol) {
  HeaderName = "f.proto.h";
  build(
      R"(// Generated by the protocol buffer compiler.  DO NOT EDIT!
         namespace nx {
           class Top_Level {};
           class TopLevel {};
           enum Kind {
             KIND_OK,
             Kind_Not_Ok,
           };
         })");
  EXPECT_TRUE(shouldCollect("nx::TopLevel"));
  EXPECT_TRUE(shouldCollect("nx::Kind::KIND_OK"));
  EXPECT_TRUE(shouldCollect("nx::Kind"));

  EXPECT_FALSE(shouldCollect("nx::Top_Level"));
  EXPECT_FALSE(shouldCollect("nx::Kind::Kind_Not_Ok"));
}

TEST_F(ShouldCollectSymbolTest, DoubleCheckProtoHeaderComment) {
  HeaderName = "f.proto.h";
  build(R"(
    namespace nx {
      class Top_Level {};
      enum Kind {
        Kind_Fine
      };
    }
  )");
  EXPECT_TRUE(shouldCollect("nx::Top_Level"));
  EXPECT_TRUE(shouldCollect("nx::Kind_Fine"));
}

class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
public:
  SymbolIndexActionFactory(SymbolCollector::Options COpts,
                           CommentHandler *PragmaHandler)
      : COpts(std::move(COpts)), PragmaHandler(PragmaHandler) {}

  std::unique_ptr<FrontendAction> create() override {
    class IndexAction : public ASTFrontendAction {
    public:
      IndexAction(std::shared_ptr<index::IndexDataConsumer> DataConsumer,
                  const index::IndexingOptions &Opts,
                  CommentHandler *PragmaHandler)
          : DataConsumer(std::move(DataConsumer)), Opts(Opts),
            PragmaHandler(PragmaHandler) {}

      std::unique_ptr<ASTConsumer>
      CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
        if (PragmaHandler)
          CI.getPreprocessor().addCommentHandler(PragmaHandler);
        return createIndexingASTConsumer(DataConsumer, Opts,
                                         CI.getPreprocessorPtr());
      }

      bool BeginInvocation(CompilerInstance &CI) override {
        // Make the compiler parse all comments.
        CI.getLangOpts().CommentOpts.ParseAllComments = true;
        return true;
      }

    private:
      std::shared_ptr<index::IndexDataConsumer> DataConsumer;
      index::IndexingOptions Opts;
      CommentHandler *PragmaHandler;
    };
    index::IndexingOptions IndexOpts;
    IndexOpts.SystemSymbolFilter =
        index::IndexingOptions::SystemSymbolFilterKind::All;
    IndexOpts.IndexFunctionLocals = false;
    Collector = std::make_shared<SymbolCollector>(COpts);
    return std::make_unique<IndexAction>(Collector, std::move(IndexOpts),
                                         PragmaHandler);
  }

  std::shared_ptr<SymbolCollector> Collector;
  SymbolCollector::Options COpts;
  CommentHandler *PragmaHandler;
};

class SymbolCollectorTest : public ::testing::Test {
public:
  SymbolCollectorTest()
      : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem),
        TestHeaderName(testPath("symbol.h")),
        TestFileName(testPath("symbol.cc")) {
    TestHeaderURI = URI::create(TestHeaderName).toString();
    TestFileURI = URI::create(TestFileName).toString();
  }

  // Note that unlike TestTU, no automatic header guard is added.
  // HeaderCode should start with #pragma once to be treated as modular.
  bool runSymbolCollector(llvm::StringRef HeaderCode, llvm::StringRef MainCode,
                          const std::vector<std::string> &ExtraArgs = {}) {
    llvm::IntrusiveRefCntPtr<FileManager> Files(
        new FileManager(FileSystemOptions(), InMemoryFileSystem));

    auto Factory = std::make_unique<SymbolIndexActionFactory>(
        CollectorOpts, PragmaHandler.get());

    std::vector<std::string> Args = {"symbol_collector", "-fsyntax-only",
                                     "-xc++", "-include", TestHeaderName};
    Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
    // This allows to override the "-xc++" with something else, i.e.
    // -xobjective-c++.
    Args.push_back(TestFileName);

    tooling::ToolInvocation Invocation(
        Args, Factory->create(), Files.get(),
        std::make_shared<PCHContainerOperations>());

    InMemoryFileSystem->addFile(TestHeaderName, 0,
                                llvm::MemoryBuffer::getMemBuffer(HeaderCode));
    InMemoryFileSystem->addFile(TestFileName, 0,
                                llvm::MemoryBuffer::getMemBuffer(MainCode));
    Invocation.run();
    Symbols = Factory->Collector->takeSymbols();
    Refs = Factory->Collector->takeRefs();
    Relations = Factory->Collector->takeRelations();
    return true;
  }

protected:
  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem;
  std::string TestHeaderName;
  std::string TestHeaderURI;
  std::string TestFileName;
  std::string TestFileURI;
  SymbolSlab Symbols;
  RefSlab Refs;
  RelationSlab Relations;
  SymbolCollector::Options CollectorOpts;
  std::unique_ptr<CommentHandler> PragmaHandler;
};

TEST_F(SymbolCollectorTest, CollectSymbols) {
  const std::string Header = R"(
    class Foo {
      Foo() {}
      Foo(int a) {}
      void f();
      friend void f1();
      friend class Friend;
      Foo& operator=(const Foo&);
      ~Foo();
      class Nested {
      void f();
      };
    };
    class Friend {
    };

    void f1();
    inline void f2() {}
    static const int KInt = 2;
    const char* kStr = "123";

    namespace {
    void ff() {} // ignore
    }

    void f1() {}

    namespace foo {
    // Type alias
    typedef int int32;
    using int32_t = int32;

    // Variable
    int v1;

    // Namespace
    namespace bar {
    int v2;
    }
    // Namespace alias
    namespace baz = bar;

    using bar::v2;
    } // namespace foo
  )";
  runSymbolCollector(Header, /*Main=*/"");
  EXPECT_THAT(Symbols,
              UnorderedElementsAreArray(
                  {AllOf(QName("Foo"), ForCodeCompletion(true)),
                   AllOf(QName("Foo::Foo"), ForCodeCompletion(false)),
                   AllOf(QName("Foo::Foo"), ForCodeCompletion(false)),
                   AllOf(QName("Foo::f"), ForCodeCompletion(false)),
                   AllOf(QName("Foo::~Foo"), ForCodeCompletion(false)),
                   AllOf(QName("Foo::operator="), ForCodeCompletion(false)),
                   AllOf(QName("Foo::Nested"), ForCodeCompletion(false)),
                   AllOf(QName("Foo::Nested::f"), ForCodeCompletion(false)),

                   AllOf(QName("Friend"), ForCodeCompletion(true)),
                   AllOf(QName("f1"), ForCodeCompletion(true)),
                   AllOf(QName("f2"), ForCodeCompletion(true)),
                   AllOf(QName("KInt"), ForCodeCompletion(true)),
                   AllOf(QName("kStr"), ForCodeCompletion(true)),
                   AllOf(QName("foo"), ForCodeCompletion(true)),
                   AllOf(QName("foo::bar"), ForCodeCompletion(true)),
                   AllOf(QName("foo::int32"), ForCodeCompletion(true)),
                   AllOf(QName("foo::int32_t"), ForCodeCompletion(true)),
                   AllOf(QName("foo::v1"), ForCodeCompletion(true)),
                   AllOf(QName("foo::bar::v2"), ForCodeCompletion(true)),
                   AllOf(QName("foo::v2"), ForCodeCompletion(true)),
                   AllOf(QName("foo::baz"), ForCodeCompletion(true))}));
}

TEST_F(SymbolCollectorTest, FileLocal) {
  const std::string Header = R"(
    class Foo {};
    namespace {
      class Ignored {};
    }
    void bar();
  )";
  const std::string Main = R"(
    class ForwardDecl;
    void bar() {}
    static void a();
    class B {};
    namespace {
      void c();
    }
  )";
  runSymbolCollector(Header, Main);
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  AllOf(QName("Foo"), VisibleOutsideFile()),
                  AllOf(QName("bar"), VisibleOutsideFile()),
                  AllOf(QName("a"), Not(VisibleOutsideFile())),
                  AllOf(QName("B"), Not(VisibleOutsideFile())),
                  AllOf(QName("c"), Not(VisibleOutsideFile())),
                  // FIXME: ForwardDecl likely *is* visible outside.
                  AllOf(QName("ForwardDecl"), Not(VisibleOutsideFile()))));
}

TEST_F(SymbolCollectorTest, Template) {
  Annotations Header(R"(
    // Primary template and explicit specialization are indexed, instantiation
    // is not.
    template <class T, class U> struct [[Tmpl]] {T $xdecl[[x]] = 0;};
    template <> struct $specdecl[[Tmpl]]<int, bool> {};
    template <class U> struct $partspecdecl[[Tmpl]]<bool, U> {};
    extern template struct Tmpl<float, bool>;
    template struct Tmpl<double, bool>;
  )");
  runSymbolCollector(Header.code(), /*Main=*/"");
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  AllOf(QName("Tmpl"), DeclRange(Header.range()),
                        ForCodeCompletion(true)),
                  AllOf(QName("Tmpl"), DeclRange(Header.range("specdecl")),
                        ForCodeCompletion(false)),
                  AllOf(QName("Tmpl"), DeclRange(Header.range("partspecdecl")),
                        ForCodeCompletion(false)),
                  AllOf(QName("Tmpl::x"), DeclRange(Header.range("xdecl")),
                        ForCodeCompletion(false))));
}

TEST_F(SymbolCollectorTest, TemplateArgs) {
  Annotations Header(R"(
    template <class X> class $barclasstemp[[Bar]] {};
    template <class T, class U, template<typename> class Z, int Q>
    struct [[Tmpl]] { T $xdecl[[x]] = 0; };

    // template-template, non-type and type full spec
    template <> struct $specdecl[[Tmpl]]<int, bool, Bar, 3> {};

    // template-template, non-type and type partial spec
    template <class U, int T> struct $partspecdecl[[Tmpl]]<bool, U, Bar, T> {};
    // instantiation
    extern template struct Tmpl<float, bool, Bar, 8>;
    // instantiation
    template struct Tmpl<double, bool, Bar, 2>;

    template <typename ...> class $fooclasstemp[[Foo]] {};
    // parameter-packs full spec
    template<> class $parampack[[Foo]]<Bar<int>, int, double> {};
    // parameter-packs partial spec
    template<class T> class $parampackpartial[[Foo]]<T, T> {};

    template <int ...> class $bazclasstemp[[Baz]] {};
    // non-type parameter-packs full spec
    template<> class $parampacknontype[[Baz]]<3, 5, 8> {};
    // non-type parameter-packs partial spec
    template<int T> class $parampacknontypepartial[[Baz]]<T, T> {};

    template <template <class> class ...> class $fozclasstemp[[Foz]] {};
    // template-template parameter-packs full spec
    template<> class $parampacktempltempl[[Foz]]<Bar, Bar> {};
    // template-template parameter-packs partial spec
    template<template <class> class T>
    class $parampacktempltemplpartial[[Foz]]<T, T> {};
  )");
  runSymbolCollector(Header.code(), /*Main=*/"");
  EXPECT_THAT(
      Symbols,
      AllOf(
          Contains(AllOf(QName("Tmpl"), TemplateArgs("<int, bool, Bar, 3>"),
                         DeclRange(Header.range("specdecl")),
                         ForCodeCompletion(false))),
          Contains(AllOf(QName("Tmpl"), TemplateArgs("<bool, U, Bar, T>"),
                         DeclRange(Header.range("partspecdecl")),
                         ForCodeCompletion(false))),
          Contains(AllOf(QName("Foo"), TemplateArgs("<Bar<int>, int, double>"),
                         DeclRange(Header.range("parampack")),
                         ForCodeCompletion(false))),
          Contains(AllOf(QName("Foo"), TemplateArgs("<T, T>"),
                         DeclRange(Header.range("parampackpartial")),
                         ForCodeCompletion(false))),
          Contains(AllOf(QName("Baz"), TemplateArgs("<3, 5, 8>"),
                         DeclRange(Header.range("parampacknontype")),
                         ForCodeCompletion(false))),
          Contains(AllOf(QName("Baz"), TemplateArgs("<T, T>"),
                         DeclRange(Header.range("parampacknontypepartial")),
                         ForCodeCompletion(false))),
          Contains(AllOf(QName("Foz"), TemplateArgs("<Bar, Bar>"),
                         DeclRange(Header.range("parampacktempltempl")),
                         ForCodeCompletion(false))),
          Contains(AllOf(QName("Foz"), TemplateArgs("<T, T>"),
                         DeclRange(Header.range("parampacktempltemplpartial")),
                         ForCodeCompletion(false)))));
}

TEST_F(SymbolCollectorTest, ObjCSymbols) {
  const std::string Header = R"(
    @interface Person
    - (void)someMethodName:(void*)name1 lastName:(void*)lName;
    @end

    @implementation Person
    - (void)someMethodName:(void*)name1 lastName:(void*)lName{
      int foo;
      ^(int param){ int bar; };
    }
    @end

    @interface Person (MyCategory)
    - (void)someMethodName2:(void*)name2;
    @end

    @implementation Person (MyCategory)
    - (void)someMethodName2:(void*)name2 {
      int foo2;
    }
    @end

    @protocol MyProtocol
    - (void)someMethodName3:(void*)name3;
    @end
  )";
  TestFileName = testPath("test.m");
  runSymbolCollector(Header, /*Main=*/"", {"-fblocks", "-xobjective-c++"});
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  QName("Person"), QName("Person::someMethodName:lastName:"),
                  QName("MyCategory"), QName("Person::someMethodName2:"),
                  QName("MyProtocol"), QName("MyProtocol::someMethodName3:")));
}

TEST_F(SymbolCollectorTest, ObjCPropertyImpl) {
  const std::string Header = R"(
    @interface Container
    @property(nonatomic) int magic;
    @end

    @implementation Container
    @end
  )";
  TestFileName = testPath("test.m");
  runSymbolCollector(Header, /*Main=*/"", {"-xobjective-c++"});
  EXPECT_THAT(Symbols, Contains(QName("Container")));
  EXPECT_THAT(Symbols, Contains(QName("Container::magic")));
  // FIXME: Results also contain Container::_magic on some platforms.
  //        Figure out why it's platform-dependent.
}

TEST_F(SymbolCollectorTest, Locations) {
  Annotations Header(R"cpp(
    // Declared in header, defined in main.
    extern int $xdecl[[X]];
    class $clsdecl[[Cls]];
    void $printdecl[[print]]();

    // Declared in header, defined nowhere.
    extern int $zdecl[[Z]];

    void $foodecl[[fo\
o]]();
  )cpp");
  Annotations Main(R"cpp(
    int $xdef[[X]] = 42;
    class $clsdef[[Cls]] {};
    void $printdef[[print]]() {}

    // Declared/defined in main only.
    int $ydecl[[Y]];
  )cpp");
  runSymbolCollector(Header.code(), Main.code());
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  AllOf(QName("X"), DeclRange(Header.range("xdecl")),
                        DefRange(Main.range("xdef"))),
                  AllOf(QName("Cls"), DeclRange(Header.range("clsdecl")),
                        DefRange(Main.range("clsdef"))),
                  AllOf(QName("print"), DeclRange(Header.range("printdecl")),
                        DefRange(Main.range("printdef"))),
                  AllOf(QName("Z"), DeclRange(Header.range("zdecl"))),
                  AllOf(QName("foo"), DeclRange(Header.range("foodecl"))),
                  AllOf(QName("Y"), DeclRange(Main.range("ydecl")))));
}

TEST_F(SymbolCollectorTest, Refs) {
  Annotations Header(R"(
  #define MACRO(X) (X + 1)
  class Foo {
  public:
    Foo() {}
    Foo(int);
  };
  class Bar;
  void func();

  namespace NS {} // namespace ref is ignored
  )");
  Annotations Main(R"(
  class $bar[[Bar]] {};

  void $func[[func]]();

  void fff() {
    $foo[[Foo]] foo;
    $bar[[Bar]] bar;
    $func[[func]]();
    int abc = 0;
    $foo[[Foo]] foo2 = abc;
    abc = $macro[[MACRO]](1);
  }
  )");
  Annotations SymbolsOnlyInMainCode(R"(
  #define FUNC(X) (X+1)
  int a;
  void b() {}
  static const int c = FUNC(1);
  class d {};
  )");
  CollectorOpts.RefFilter = RefKind::All;
  CollectorOpts.CollectMacro = true;
  runSymbolCollector(Header.code(),
                     (Main.code() + SymbolsOnlyInMainCode.code()).str());
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "Foo").ID,
                                  HaveRanges(Main.ranges("foo")))));
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "Bar").ID,
                                  HaveRanges(Main.ranges("bar")))));
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "func").ID,
                                  HaveRanges(Main.ranges("func")))));
  EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(Symbols, "NS").ID, _))));
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "MACRO").ID,
                                  HaveRanges(Main.ranges("macro")))));
  // Symbols *only* in the main file (a, b, c, FUNC) had no refs collected.
  auto MainSymbols =
      TestTU::withHeaderCode(SymbolsOnlyInMainCode.code()).headerSymbols();
  EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(MainSymbols, "a").ID, _))));
  EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(MainSymbols, "b").ID, _))));
  EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(MainSymbols, "c").ID, _))));
  EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(MainSymbols, "FUNC").ID, _))));
}

TEST_F(SymbolCollectorTest, MacroRefInHeader) {
  Annotations Header(R"(
  #define $foo[[FOO]](X) (X + 1)
  #define $bar[[BAR]](X) (X + 2)

  // Macro defined multiple times.
  #define $ud1[[UD]] 1
  int ud_1 = $ud1[[UD]];
  #undef UD

  #define $ud2[[UD]] 2
  int ud_2 = $ud2[[UD]];
  #undef UD

  // Macros from token concatenations not included.
  #define $concat[[CONCAT]](X) X##A()
  #define $prepend[[PREPEND]](X) MACRO##X()
  #define $macroa[[MACROA]]() 123
  int B = $concat[[CONCAT]](MACRO);
  int D = $prepend[[PREPEND]](A);

  void fff() {
    int abc = $foo[[FOO]](1) + $bar[[BAR]]($foo[[FOO]](1));
  }
  )");
  CollectorOpts.RefFilter = RefKind::All;
  CollectorOpts.RefsInHeaders = true;
  // Need this to get the SymbolID for macros for tests.
  CollectorOpts.CollectMacro = true;

  runSymbolCollector(Header.code(), "");

  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "FOO").ID,
                                  HaveRanges(Header.ranges("foo")))));
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "BAR").ID,
                                  HaveRanges(Header.ranges("bar")))));
  // No unique ID for multiple symbols named UD. Check for ranges only.
  EXPECT_THAT(Refs, Contains(Pair(_, HaveRanges(Header.ranges("ud1")))));
  EXPECT_THAT(Refs, Contains(Pair(_, HaveRanges(Header.ranges("ud2")))));
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "CONCAT").ID,
                                  HaveRanges(Header.ranges("concat")))));
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "PREPEND").ID,
                                  HaveRanges(Header.ranges("prepend")))));
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "MACROA").ID,
                                  HaveRanges(Header.ranges("macroa")))));
}

TEST_F(SymbolCollectorTest, MacroRefWithoutCollectingSymbol) {
  Annotations Header(R"(
  #define $foo[[FOO]](X) (X + 1)
  int abc = $foo[[FOO]](1);
  )");
  CollectorOpts.RefFilter = RefKind::All;
  CollectorOpts.RefsInHeaders = true;
  CollectorOpts.CollectMacro = false;
  runSymbolCollector(Header.code(), "");
  EXPECT_THAT(Refs, Contains(Pair(_, HaveRanges(Header.ranges("foo")))));
}

TEST_F(SymbolCollectorTest, MacrosWithRefFilter) {
  Annotations Header("#define $macro[[MACRO]](X) (X + 1)");
  Annotations Main("void foo() { int x = $macro[[MACRO]](1); }");
  CollectorOpts.RefFilter = RefKind::Unknown;
  runSymbolCollector(Header.code(), Main.code());
  EXPECT_THAT(Refs, IsEmpty());
}

TEST_F(SymbolCollectorTest, NameReferences) {
  CollectorOpts.RefFilter = RefKind::All;
  CollectorOpts.RefsInHeaders = true;
  Annotations Header(R"(
    class [[Foo]] {
    public:
      [[Foo]]() {}
      ~[[Foo]]() {}
    };
  )");
  CollectorOpts.RefFilter = RefKind::All;
  runSymbolCollector(Header.code(), "");
  // When we find references for class Foo, we expect to see all
  // constructor/destructor references.
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "Foo").ID,
                                  HaveRanges(Header.ranges()))));
}

TEST_F(SymbolCollectorTest, RefsOnMacros) {
  // Refs collected from SymbolCollector behave in the same way as
  // AST-based xrefs.
  CollectorOpts.RefFilter = RefKind::All;
  CollectorOpts.RefsInHeaders = true;
  Annotations Header(R"(
    #define TYPE(X) X
    #define FOO Foo
    #define CAT(X, Y) X##Y
    class [[Foo]] {};
    void test() {
      TYPE([[Foo]]) foo;
      [[FOO]] foo2;
      TYPE(TYPE([[Foo]])) foo3;
      [[CAT]](Fo, o) foo4;
    }
  )");
  CollectorOpts.RefFilter = RefKind::All;
  runSymbolCollector(Header.code(), "");
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "Foo").ID,
                                  HaveRanges(Header.ranges()))));
}

TEST_F(SymbolCollectorTest, HeaderAsMainFile) {
  CollectorOpts.RefFilter = RefKind::All;
  Annotations Header(R"(
  class $Foo[[Foo]] {};

  void $Func[[Func]]() {
    $Foo[[Foo]] fo;
  }
  )");
  // The main file is normal .cpp file, we shouldn't collect any refs of symbols
  // which are not declared in the preamble.
  TestFileName = testPath("foo.cpp");
  runSymbolCollector("", Header.code());
  EXPECT_THAT(Refs, UnorderedElementsAre());

  // Run the .h file as main file, we should collect the refs.
  TestFileName = testPath("foo.h");
  runSymbolCollector("", Header.code(),
                     /*ExtraArgs=*/{"-xobjective-c++-header"});
  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Foo"), QName("Func")));
  EXPECT_THAT(Refs,
              UnorderedElementsAre(Pair(findSymbol(Symbols, "Foo").ID,
                                        HaveRanges(Header.ranges("Foo"))),
                                   Pair(findSymbol(Symbols, "Func").ID,
                                        HaveRanges(Header.ranges("Func")))));

  // Run the .hh file as main file (without "-x c++-header"), we should collect
  // the refs as well.
  TestFileName = testPath("foo.hh");
  runSymbolCollector("", Header.code());
  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Foo"), QName("Func")));
  EXPECT_THAT(Refs,
              UnorderedElementsAre(Pair(findSymbol(Symbols, "Foo").ID,
                                        HaveRanges(Header.ranges("Foo"))),
                                   Pair(findSymbol(Symbols, "Func").ID,
                                        HaveRanges(Header.ranges("Func")))));
}

TEST_F(SymbolCollectorTest, RefsInHeaders) {
  CollectorOpts.RefFilter = RefKind::All;
  CollectorOpts.RefsInHeaders = true;
  CollectorOpts.CollectMacro = true;
  Annotations Header(R"(
  #define $macro[[MACRO]](x) (x+1)
  class $foo[[Foo]] {};
  )");
  runSymbolCollector(Header.code(), "");
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "Foo").ID,
                                  HaveRanges(Header.ranges("foo")))));
  EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "MACRO").ID,
                                  HaveRanges(Header.ranges("macro")))));
}

TEST_F(SymbolCollectorTest, Relations) {
  std::string Header = R"(
  class Base {};
  class Derived : public Base {};
  )";
  runSymbolCollector(Header, /*Main=*/"");
  const Symbol &Base = findSymbol(Symbols, "Base");
  const Symbol &Derived = findSymbol(Symbols, "Derived");
  EXPECT_THAT(Relations,
              Contains(Relation{Base.ID, RelationKind::BaseOf, Derived.ID}));
}

TEST_F(SymbolCollectorTest, CountReferences) {
  const std::string Header = R"(
    class W;
    class X {};
    class Y;
    class Z {}; // not used anywhere
    Y* y = nullptr;  // used in header doesn't count
    #define GLOBAL_Z(name) Z name;
  )";
  const std::string Main = R"(
    W* w = nullptr;
    W* w2 = nullptr; // only one usage counts
    X x();
    class V;
    class Y{}; // definition doesn't count as a reference
    V* v = nullptr;
    GLOBAL_Z(z); // Not a reference to Z, we don't spell the type.
  )";
  CollectorOpts.CountReferences = true;
  runSymbolCollector(Header, Main);
  EXPECT_THAT(
      Symbols,
      UnorderedElementsAreArray(
          {AllOf(QName("W"), RefCount(1)), AllOf(QName("X"), RefCount(1)),
           AllOf(QName("Y"), RefCount(0)), AllOf(QName("Z"), RefCount(0)),
           AllOf(QName("y"), RefCount(0)), AllOf(QName("z"), RefCount(0)),
           AllOf(QName("x"), RefCount(0)), AllOf(QName("w"), RefCount(0)),
           AllOf(QName("w2"), RefCount(0)), AllOf(QName("V"), RefCount(1)),
           AllOf(QName("v"), RefCount(0))}));
}

TEST_F(SymbolCollectorTest, SymbolRelativeNoFallback) {
  runSymbolCollector("class Foo {};", /*Main=*/"");
  EXPECT_THAT(Symbols, UnorderedElementsAre(
                           AllOf(QName("Foo"), DeclURI(TestHeaderURI))));
}

TEST_F(SymbolCollectorTest, SymbolRelativeWithFallback) {
  TestHeaderName = "x.h";
  TestFileName = "x.cpp";
  TestHeaderURI = URI::create(testPath(TestHeaderName)).toString();
  CollectorOpts.FallbackDir = testRoot();
  runSymbolCollector("class Foo {};", /*Main=*/"");
  EXPECT_THAT(Symbols, UnorderedElementsAre(
                           AllOf(QName("Foo"), DeclURI(TestHeaderURI))));
}

TEST_F(SymbolCollectorTest, UnittestURIScheme) {
  // Use test URI scheme from URITests.cpp
  TestHeaderName = testPath("x.h");
  TestFileName = testPath("x.cpp");
  runSymbolCollector("class Foo {};", /*Main=*/"");
  EXPECT_THAT(Symbols, UnorderedElementsAre(
                           AllOf(QName("Foo"), DeclURI("unittest:///x.h"))));
}

TEST_F(SymbolCollectorTest, IncludeEnums) {
  const std::string Header = R"(
    enum {
      Red
    };
    enum Color {
      Green
    };
    enum class Color2 {
      Yellow
    };
    namespace ns {
    enum {
      Black
    };
    }
  )";
  runSymbolCollector(Header, /*Main=*/"");
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  AllOf(QName("Red"), ForCodeCompletion(true)),
                  AllOf(QName("Color"), ForCodeCompletion(true)),
                  AllOf(QName("Green"), ForCodeCompletion(true)),
                  AllOf(QName("Color2"), ForCodeCompletion(true)),
                  AllOf(QName("Color2::Yellow"), ForCodeCompletion(false)),
                  AllOf(QName("ns"), ForCodeCompletion(true)),
                  AllOf(QName("ns::Black"), ForCodeCompletion(true))));
}

TEST_F(SymbolCollectorTest, NamelessSymbols) {
  const std::string Header = R"(
    struct {
      int a;
    } Foo;
  )";
  runSymbolCollector(Header, /*Main=*/"");
  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Foo"),
                                            QName("(anonymous struct)::a")));
}

TEST_F(SymbolCollectorTest, SymbolFormedFromRegisteredSchemeFromMacro) {

  Annotations Header(R"(
    #define FF(name) \
      class name##_Test {};

    $expansion[[FF]](abc);

    #define FF2() \
      class $spelling[[Test]] {};

    FF2();
  )");

  runSymbolCollector(Header.code(), /*Main=*/"");
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  AllOf(QName("abc_Test"), DeclRange(Header.range("expansion")),
                        DeclURI(TestHeaderURI)),
                  AllOf(QName("Test"), DeclRange(Header.range("spelling")),
                        DeclURI(TestHeaderURI))));
}

TEST_F(SymbolCollectorTest, SymbolFormedByCLI) {
  Annotations Header(R"(
    #ifdef NAME
    class $expansion[[NAME]] {};
    #endif
  )");
  runSymbolCollector(Header.code(), /*Main=*/"", /*ExtraArgs=*/{"-DNAME=name"});
  EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(
                           QName("name"), DeclRange(Header.range("expansion")),
                           DeclURI(TestHeaderURI))));
}

TEST_F(SymbolCollectorTest, SymbolsInMainFile) {
  const std::string Main = R"(
    class Foo {};
    void f1();
    inline void f2() {}

    namespace {
    void ff() {}
    }
    namespace foo {
    namespace {
    class Bar {};
    }
    }
    void main_f() {}
    void f1() {}
  )";
  runSymbolCollector(/*Header=*/"", Main);
  EXPECT_THAT(Symbols, UnorderedElementsAre(
                           QName("Foo"), QName("f1"), QName("f2"), QName("ff"),
                           QName("foo"), QName("foo::Bar"), QName("main_f")));
}

TEST_F(SymbolCollectorTest, Documentation) {
  const std::string Header = R"(
    // Doc Foo
    class Foo {
      // Doc f
      int f();
    };
  )";
  CollectorOpts.StoreAllDocumentation = false;
  runSymbolCollector(Header, /* Main */ "");
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  AllOf(QName("Foo"), Doc("Doc Foo"), ForCodeCompletion(true)),
                  AllOf(QName("Foo::f"), Doc(""), ReturnType(""),
                        ForCodeCompletion(false))));

  CollectorOpts.StoreAllDocumentation = true;
  runSymbolCollector(Header, /* Main */ "");
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  AllOf(QName("Foo"), Doc("Doc Foo"), ForCodeCompletion(true)),
                  AllOf(QName("Foo::f"), Doc("Doc f"), ReturnType(""),
                        ForCodeCompletion(false))));
}

TEST_F(SymbolCollectorTest, ClassMembers) {
  const std::string Header = R"(
    class Foo {
      void f() {}
      void g();
      static void sf() {}
      static void ssf();
      static int x;
    };
  )";
  const std::string Main = R"(
    void Foo::g() {}
    void Foo::ssf() {}
  )";
  runSymbolCollector(Header, Main);
  EXPECT_THAT(
      Symbols,
      UnorderedElementsAre(
          QName("Foo"),
          AllOf(QName("Foo::f"), ReturnType(""), ForCodeCompletion(false)),
          AllOf(QName("Foo::g"), ReturnType(""), ForCodeCompletion(false)),
          AllOf(QName("Foo::sf"), ReturnType(""), ForCodeCompletion(false)),
          AllOf(QName("Foo::ssf"), ReturnType(""), ForCodeCompletion(false)),
          AllOf(QName("Foo::x"), ReturnType(""), ForCodeCompletion(false))));
}

TEST_F(SymbolCollectorTest, Scopes) {
  const std::string Header = R"(
    namespace na {
    class Foo {};
    namespace nb {
    class Bar {};
    }
    }
  )";
  runSymbolCollector(Header, /*Main=*/"");
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(QName("na"), QName("na::nb"),
                                   QName("na::Foo"), QName("na::nb::Bar")));
}

TEST_F(SymbolCollectorTest, ExternC) {
  const std::string Header = R"(
    extern "C" { class Foo {}; }
    namespace na {
    extern "C" { class Bar {}; }
    }
  )";
  runSymbolCollector(Header, /*Main=*/"");
  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("na"), QName("Foo"),
                                            QName("na::Bar")));
}

TEST_F(SymbolCollectorTest, SkipInlineNamespace) {
  const std::string Header = R"(
    namespace na {
    inline namespace nb {
    class Foo {};
    }
    }
    namespace na {
    // This is still inlined.
    namespace nb {
    class Bar {};
    }
    }
  )";
  runSymbolCollector(Header, /*Main=*/"");
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(QName("na"), QName("na::nb"),
                                   QName("na::Foo"), QName("na::Bar")));
}

TEST_F(SymbolCollectorTest, SymbolWithDocumentation) {
  const std::string Header = R"(
    namespace nx {
    /// Foo comment.
    int ff(int x, double y) { return 0; }
    }
  )";
  runSymbolCollector(Header, /*Main=*/"");
  EXPECT_THAT(
      Symbols,
      UnorderedElementsAre(
          QName("nx"), AllOf(QName("nx::ff"), Labeled("ff(int x, double y)"),
                             ReturnType("int"), Doc("Foo comment."))));
}

TEST_F(SymbolCollectorTest, Snippet) {
  const std::string Header = R"(
    namespace nx {
    void f() {}
    int ff(int x, double y) { return 0; }
    }
  )";
  runSymbolCollector(Header, /*Main=*/"");
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  QName("nx"),
                  AllOf(QName("nx::f"), Labeled("f()"), Snippet("f()")),
                  AllOf(QName("nx::ff"), Labeled("ff(int x, double y)"),
                        Snippet("ff(${1:int x}, ${2:double y})"))));
}

TEST_F(SymbolCollectorTest, IncludeHeaderSameAsFileURI) {
  CollectorOpts.CollectIncludePath = true;
  runSymbolCollector("#pragma once\nclass Foo {};", /*Main=*/"");
  EXPECT_THAT(Symbols, UnorderedElementsAre(
                           AllOf(QName("Foo"), DeclURI(TestHeaderURI))));
  EXPECT_THAT(Symbols.begin()->IncludeHeaders,
              UnorderedElementsAre(IncludeHeaderWithRef(TestHeaderURI, 1u)));
}

TEST_F(SymbolCollectorTest, CanonicalSTLHeader) {
  CollectorOpts.CollectIncludePath = true;
  CanonicalIncludes Includes;
  auto Language = LangOptions();
  Language.CPlusPlus = true;
  Includes.addSystemHeadersMapping(Language);
  CollectorOpts.Includes = &Includes;
  runSymbolCollector("namespace std { class string {}; }", /*Main=*/"");
  EXPECT_THAT(Symbols,
              Contains(AllOf(QName("std::string"), DeclURI(TestHeaderURI),
                             IncludeHeader("<string>"))));
}

TEST_F(SymbolCollectorTest, IWYUPragma) {
  CollectorOpts.CollectIncludePath = true;
  CanonicalIncludes Includes;
  PragmaHandler = collectIWYUHeaderMaps(&Includes);
  CollectorOpts.Includes = &Includes;
  const std::string Header = R"(
    // IWYU pragma: private, include the/good/header.h
    class Foo {};
  )";
  runSymbolCollector(Header, /*Main=*/"");
  EXPECT_THAT(Symbols, UnorderedElementsAre(
                           AllOf(QName("Foo"), DeclURI(TestHeaderURI),
                                 IncludeHeader("\"the/good/header.h\""))));
}

TEST_F(SymbolCollectorTest, IWYUPragmaWithDoubleQuotes) {
  CollectorOpts.CollectIncludePath = true;
  CanonicalIncludes Includes;
  PragmaHandler = collectIWYUHeaderMaps(&Includes);
  CollectorOpts.Includes = &Includes;
  const std::string Header = R"(
    // IWYU pragma: private, include "the/good/header.h"
    class Foo {};
  )";
  runSymbolCollector(Header, /*Main=*/"");
  EXPECT_THAT(Symbols, UnorderedElementsAre(
                           AllOf(QName("Foo"), DeclURI(TestHeaderURI),
                                 IncludeHeader("\"the/good/header.h\""))));
}

TEST_F(SymbolCollectorTest, SkipIncFileWhenCanonicalizeHeaders) {
  CollectorOpts.CollectIncludePath = true;
  CanonicalIncludes Includes;
  Includes.addMapping(TestHeaderName, "<canonical>");
  CollectorOpts.Includes = &Includes;
  auto IncFile = testPath("test.inc");
  auto IncURI = URI::create(IncFile).toString();
  InMemoryFileSystem->addFile(IncFile, 0,
                              llvm::MemoryBuffer::getMemBuffer("class X {};"));
  runSymbolCollector("#include \"test.inc\"\nclass Y {};", /*Main=*/"",
                     /*ExtraArgs=*/{"-I", testRoot()});
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(AllOf(QName("X"), DeclURI(IncURI),
                                         IncludeHeader("<canonical>")),
                                   AllOf(QName("Y"), DeclURI(TestHeaderURI),
                                         IncludeHeader("<canonical>"))));
}

TEST_F(SymbolCollectorTest, MainFileIsHeaderWhenSkipIncFile) {
  CollectorOpts.CollectIncludePath = true;
  // To make this case as hard as possible, we won't tell clang main is a
  // header. No extension, no -x c++-header.
  TestFileName = testPath("no_ext_main");
  TestFileURI = URI::create(TestFileName).toString();
  auto IncFile = testPath("test.inc");
  auto IncURI = URI::create(IncFile).toString();
  InMemoryFileSystem->addFile(IncFile, 0,
                              llvm::MemoryBuffer::getMemBuffer("class X {};"));
  runSymbolCollector("", R"cpp(
    // Can't use #pragma once in a main file clang doesn't think is a header.
    #ifndef MAIN_H_
    #define MAIN_H_
    #include "test.inc"
    #endif
  )cpp",
                     /*ExtraArgs=*/{"-I", testRoot()});
  EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(QName("X"), DeclURI(IncURI),
                                                  IncludeHeader(TestFileURI))));
}

TEST_F(SymbolCollectorTest, IncFileInNonHeader) {
  CollectorOpts.CollectIncludePath = true;
  TestFileName = testPath("main.cc");
  TestFileURI = URI::create(TestFileName).toString();
  auto IncFile = testPath("test.inc");
  auto IncURI = URI::create(IncFile).toString();
  InMemoryFileSystem->addFile(IncFile, 0,
                              llvm::MemoryBuffer::getMemBuffer("class X {};"));
  runSymbolCollector("", R"cpp(
    #include "test.inc"
  )cpp",
                     /*ExtraArgs=*/{"-I", testRoot()});
  EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(QName("X"), DeclURI(IncURI),
                                                  Not(IncludeHeader()))));
}

// Features that depend on header-guards are fragile. Header guards are only
// recognized when the file ends, so we have to defer checking for them.
TEST_F(SymbolCollectorTest, HeaderGuardDetected) {
  CollectorOpts.CollectIncludePath = true;
  CollectorOpts.CollectMacro = true;
  runSymbolCollector(R"cpp(
    #ifndef HEADER_GUARD_
    #define HEADER_GUARD_

    // Symbols are seen before the header guard is complete.
    #define MACRO
    int decl();

    #endif // Header guard is recognized here.
  )cpp",
                     "");
  EXPECT_THAT(Symbols, Not(Contains(QName("HEADER_GUARD_"))));
  EXPECT_THAT(Symbols, Each(IncludeHeader()));
}

TEST_F(SymbolCollectorTest, NonModularHeader) {
  auto TU = TestTU::withHeaderCode("int x();");
  EXPECT_THAT(TU.headerSymbols(), ElementsAre(IncludeHeader()));

  // Files missing include guards aren't eligible for insertion.
  TU.ImplicitHeaderGuard = false;
  EXPECT_THAT(TU.headerSymbols(), ElementsAre(Not(IncludeHeader())));

  // We recognize some patterns of trying to prevent insertion.
  TU = TestTU::withHeaderCode(R"cpp(
#ifndef SECRET
#error "This file isn't safe to include directly"
#endif
    int x();
    )cpp");
  TU.ExtraArgs.push_back("-DSECRET"); // *we're* able to include it.
  EXPECT_THAT(TU.headerSymbols(), ElementsAre(Not(IncludeHeader())));
}

TEST_F(SymbolCollectorTest, AvoidUsingFwdDeclsAsCanonicalDecls) {
  CollectorOpts.CollectIncludePath = true;
  Annotations Header(R"(
    #pragma once
    // Forward declarations of TagDecls.
    class C;
    struct S;
    union U;

    // Canonical declarations.
    class $cdecl[[C]] {};
    struct $sdecl[[S]] {};
    union $udecl[[U]] {int $xdecl[[x]]; bool $ydecl[[y]];};
  )");
  runSymbolCollector(Header.code(), /*Main=*/"");
  EXPECT_THAT(
      Symbols,
      UnorderedElementsAre(
          AllOf(QName("C"), DeclURI(TestHeaderURI),
                DeclRange(Header.range("cdecl")), IncludeHeader(TestHeaderURI),
                DefURI(TestHeaderURI), DefRange(Header.range("cdecl"))),
          AllOf(QName("S"), DeclURI(TestHeaderURI),
                DeclRange(Header.range("sdecl")), IncludeHeader(TestHeaderURI),
                DefURI(TestHeaderURI), DefRange(Header.range("sdecl"))),
          AllOf(QName("U"), DeclURI(TestHeaderURI),
                DeclRange(Header.range("udecl")), IncludeHeader(TestHeaderURI),
                DefURI(TestHeaderURI), DefRange(Header.range("udecl"))),
          AllOf(QName("U::x"), DeclURI(TestHeaderURI),
                DeclRange(Header.range("xdecl")), DefURI(TestHeaderURI),
                DefRange(Header.range("xdecl"))),
          AllOf(QName("U::y"), DeclURI(TestHeaderURI),
                DeclRange(Header.range("ydecl")), DefURI(TestHeaderURI),
                DefRange(Header.range("ydecl")))));
}

TEST_F(SymbolCollectorTest, ClassForwardDeclarationIsCanonical) {
  CollectorOpts.CollectIncludePath = true;
  runSymbolCollector(/*Header=*/"#pragma once\nclass X;",
                     /*Main=*/"class X {};");
  EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(
                           QName("X"), DeclURI(TestHeaderURI),
                           IncludeHeader(TestHeaderURI), DefURI(TestFileURI))));
}

TEST_F(SymbolCollectorTest, UTF16Character) {
  // ö is 2-bytes.
  Annotations Header(/*Header=*/"class [[pörk]] {};");
  runSymbolCollector(Header.code(), /*Main=*/"");
  EXPECT_THAT(Symbols, UnorderedElementsAre(
                           AllOf(QName("pörk"), DeclRange(Header.range()))));
}

TEST_F(SymbolCollectorTest, DoNotIndexSymbolsInFriendDecl) {
  Annotations Header(R"(
    namespace nx {
      class $z[[Z]] {};
      class X {
        friend class Y;
        friend class Z;
        friend void foo();
        friend void $bar[[bar]]() {}
      };
      class $y[[Y]] {};
      void $foo[[foo]]();
    }
  )");
  runSymbolCollector(Header.code(), /*Main=*/"");

  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  QName("nx"), QName("nx::X"),
                  AllOf(QName("nx::Y"), DeclRange(Header.range("y"))),
                  AllOf(QName("nx::Z"), DeclRange(Header.range("z"))),
                  AllOf(QName("nx::foo"), DeclRange(Header.range("foo"))),
                  AllOf(QName("nx::bar"), DeclRange(Header.range("bar")))));
}

TEST_F(SymbolCollectorTest, ReferencesInFriendDecl) {
  const std::string Header = R"(
    class X;
    class Y;
  )";
  const std::string Main = R"(
    class C {
      friend ::X;
      friend class Y;
    };
  )";
  CollectorOpts.CountReferences = true;
  runSymbolCollector(Header, Main);
  EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(QName("X"), RefCount(1)),
                                            AllOf(QName("Y"), RefCount(1)),
                                            AllOf(QName("C"), RefCount(0))));
}

TEST_F(SymbolCollectorTest, Origin) {
  CollectorOpts.Origin = SymbolOrigin::Static;
  runSymbolCollector("class Foo {};", /*Main=*/"");
  EXPECT_THAT(Symbols, UnorderedElementsAre(
                           Field(&Symbol::Origin, SymbolOrigin::Static)));
}

TEST_F(SymbolCollectorTest, CollectMacros) {
  CollectorOpts.CollectIncludePath = true;
  Annotations Header(R"(
    #pragma once
    #define X 1
    #define $mac[[MAC]](x) int x
    #define $used[[USED]](y) float y;

    MAC(p);
  )");

  Annotations Main(R"(
    #define $main[[MAIN]] 1
     USED(t);
  )");
  CollectorOpts.CountReferences = true;
  CollectorOpts.CollectMacro = true;
  runSymbolCollector(Header.code(), Main.code());
  EXPECT_THAT(
      Symbols,
      UnorderedElementsAre(
          QName("p"), QName("t"),
          AllOf(QName("X"), DeclURI(TestHeaderURI),
                IncludeHeader(TestHeaderURI)),
          AllOf(Labeled("MAC(x)"), RefCount(0),

                DeclRange(Header.range("mac")), VisibleOutsideFile()),
          AllOf(Labeled("USED(y)"), RefCount(1),
                DeclRange(Header.range("used")), VisibleOutsideFile()),
          AllOf(Labeled("MAIN"), RefCount(0), DeclRange(Main.range("main")),
                Not(VisibleOutsideFile()))));
}

TEST_F(SymbolCollectorTest, DeprecatedSymbols) {
  const std::string Header = R"(
    void TestClangc() __attribute__((deprecated("", "")));
    void TestClangd();
  )";
  runSymbolCollector(Header, /**/ "");
  EXPECT_THAT(Symbols, UnorderedElementsAre(
                           AllOf(QName("TestClangc"), Deprecated()),
                           AllOf(QName("TestClangd"), Not(Deprecated()))));
}

TEST_F(SymbolCollectorTest, ImplementationDetail) {
  const std::string Header = R"(
    #define DECL_NAME(x, y) x##_##y##_Decl
    #define DECL(x, y) class DECL_NAME(x, y) {};
    DECL(X, Y); // X_Y_Decl

    class Public {};
  )";
  runSymbolCollector(Header, /**/ "");
  EXPECT_THAT(Symbols,
              UnorderedElementsAre(
                  AllOf(QName("X_Y_Decl"), ImplementationDetail()),
                  AllOf(QName("Public"), Not(ImplementationDetail()))));
}

TEST_F(SymbolCollectorTest, UsingDecl) {
  const char *Header = R"(
  void foo();
  namespace std {
    using ::foo;
  })";
  runSymbolCollector(Header, /**/ "");
  EXPECT_THAT(Symbols, Contains(QName("std::foo")));
}

TEST_F(SymbolCollectorTest, CBuiltins) {
  // In C, printf in stdio.h is a redecl of an implicit builtin.
  const char *Header = R"(
    extern int printf(const char*, ...);
  )";
  runSymbolCollector(Header, /**/ "", {"-xc"});
  EXPECT_THAT(Symbols, Contains(QName("printf")));
}

TEST_F(SymbolCollectorTest, InvalidSourceLoc) {
  const char *Header = R"(
      void operator delete(void*)
        __attribute__((__externally_visible__));)";
  runSymbolCollector(Header, /**/ "");
  EXPECT_THAT(Symbols, Contains(QName("operator delete")));
}

} // namespace
} // namespace clangd
} // namespace clang