1//===--- tools/extra/clang-tidy/GlobList.cpp ------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "GlobList.h"
10#include "llvm/ADT/STLExtras.h"
11#include "llvm/ADT/SmallString.h"
12
13namespace clang::tidy {
14
15// Returns true if GlobList starts with the negative indicator ('-'), removes it
16// from the GlobList.
17static bool consumeNegativeIndicator(StringRef &GlobList) {
18 GlobList = GlobList.trim();
19 return GlobList.consume_front(Prefix: "-");
20}
21
22// Converts first glob from the comma-separated list of globs to Regex and
23// removes it and the trailing comma from the GlobList.
24static llvm::Regex consumeGlob(StringRef &GlobList) {
25 StringRef UntrimmedGlob = GlobList.substr(Start: 0, N: GlobList.find_first_of(Chars: ",\n"));
26 StringRef Glob = UntrimmedGlob.trim();
27 GlobList = GlobList.substr(Start: UntrimmedGlob.size() + 1);
28 SmallString<128> RegexText("^");
29 StringRef MetaChars("()^$|*+?.[]\\{}");
30 for (char C : Glob) {
31 if (C == '*')
32 RegexText.push_back(Elt: '.');
33 else if (MetaChars.contains(C))
34 RegexText.push_back(Elt: '\\');
35 RegexText.push_back(Elt: C);
36 }
37 RegexText.push_back(Elt: '$');
38 return {RegexText.str()};
39}
40
41GlobList::GlobList(StringRef Globs, bool KeepNegativeGlobs /* =true */) {
42 Items.reserve(N: Globs.count(C: ',') + Globs.count(C: '\n') + 1);
43 do {
44 GlobListItem Item;
45 Item.IsPositive = !consumeNegativeIndicator(GlobList&: Globs);
46 Item.Regex = consumeGlob(GlobList&: Globs);
47 if (Item.IsPositive || KeepNegativeGlobs)
48 Items.push_back(Elt: std::move(Item));
49 } while (!Globs.empty());
50}
51
52bool GlobList::contains(StringRef S) const {
53 // Iterating the container backwards as the last match determins if S is in
54 // the list.
55 for (const GlobListItem &Item : llvm::reverse(C: Items)) {
56 if (Item.Regex.match(String: S))
57 return Item.IsPositive;
58 }
59 return false;
60}
61
62bool CachedGlobList::contains(StringRef S) const {
63 auto Entry = Cache.try_emplace(Key: S);
64 bool &Value = Entry.first->getValue();
65 // If the entry was just inserted, determine its required value.
66 if (Entry.second)
67 Value = GlobList::contains(S);
68 return Value;
69}
70
71} // namespace clang::tidy
72

source code of clang-tools-extra/clang-tidy/GlobList.cpp