aboutsummaryrefslogtreecommitdiff
path: root/filter.cc
blob: aa6f10a9e2717feb8a162e359042b1bedc31a20d (plain)
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
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// -*- mode: C++ -*-
//
// Copyright 2022-2023 Google LLC
//
// Licensed under the Apache License v2.0 with LLVM Exceptions (the
// "License"); you may not use this file except in compliance with the
// License.  You may obtain a copy of the License at
//
//     https://llvm.org/LICENSE.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Giuliano Procida

#include "filter.h"

#include <fnmatch.h>

#include <array>
#include <cctype>
#include <cstddef>
#include <cstring>
#include <fstream>
#include <memory>
#include <ostream>
#include <queue>
#include <sstream>
#include <string>
#include <string_view>
#include <unordered_set>
#include <utility>

#include "error.h"

namespace stg {
namespace {

using Items = std::unordered_set<std::string>;

Items ReadAbigail(const std::string& filename) {
  static constexpr std::string_view kSectionSuffix = "list";
  Items items;
  std::ifstream file(filename);
  Check(file.good()) << "error opening filter file '" << filename << ": "
                     << Error(errno);
  bool in_filter_section = false;
  std::string line;
  while (std::getline(file, line)) {
    size_t start = 0;
    size_t limit = line.size();
    // Strip leading whitespace.
    while (start < limit && std::isspace(line[start])) {
      ++start;
    }
    // Skip comment lines.
    if (start < limit && line[start] == '#') {
      continue;
    }
    // Strip trailing whitespace.
    while (start < limit && std::isspace(line[limit - 1])) {
      --limit;
    }
    // Skip empty lines.
    if (start == limit) {
      continue;
    }
    // See if we are entering a filter list section.
    if (line[start] == '[' && line[limit - 1] == ']') {
      std::string_view section(&line[start + 1], limit - start - 2);
      // TODO: use std::string_view::ends_with
      const auto section_size = section.size();
      const auto suffix_size = kSectionSuffix.size();
      in_filter_section = section_size >= suffix_size &&
          section.substr(section_size - suffix_size) == kSectionSuffix;
      continue;
    }
    // Add item.
    if (in_filter_section) {
      items.insert(std::string(&line[start], limit - start));
    }
  }
  Check(file.eof()) << "error reading filter file '" << filename << ": "
                    << Error(errno);
  return items;
}

// Inverted filter.
class NotFilter : public Filter {
 public:
  explicit NotFilter(std::unique_ptr<Filter> filter)
      : filter_(std::move(filter)) {}
  bool operator()(const std::string& item) const final {
    return !(*filter_)(item);
  };

 private:
  const std::unique_ptr<Filter> filter_;
};

// Conjunction of filters.
class AndFilter : public Filter {
 public:
  AndFilter(std::unique_ptr<Filter> filter1,
            std::unique_ptr<Filter> filter2)
      : filter1_(std::move(filter1)), filter2_(std::move(filter2)) {}
  bool operator()(const std::string& item) const final {
    return (*filter1_)(item) && (*filter2_)(item);
  };

 private:
  const std::unique_ptr<Filter> filter1_;
  const std::unique_ptr<Filter> filter2_;
};

// Disjunction of filters.
class OrFilter : public Filter {
 public:
  OrFilter(std::unique_ptr<Filter> filter1,
           std::unique_ptr<Filter> filter2)
      : filter1_(std::move(filter1)), filter2_(std::move(filter2)) {}
  bool operator()(const std::string& item) const final {
    return (*filter1_)(item) || (*filter2_)(item);
  };

 private:
  const std::unique_ptr<Filter> filter1_;
  const std::unique_ptr<Filter> filter2_;
};

// Glob filter.
class GlobFilter : public Filter {
 public:
  explicit GlobFilter(const std::string& pattern) : pattern_(pattern) {}
  bool operator()(const std::string& item) const final {
    return fnmatch(pattern_.c_str(), item.c_str(), 0) == 0;
  }

 private:
  const std::string pattern_;
};

// Literal list filter.
class SetFilter : public Filter {
 public:
  explicit SetFilter(Items&& items)
      : items_(std::move(items)) {}
  bool operator()(const std::string& item) const final {
    return items_.count(item) > 0;
  };

 private:
  const Items items_;
};

const char* kTokenCharacters = ":!()&|";

// Split a filter expression into tokens.
//
// All tokens are just strings, but single characters from kTokenCharacters are
// recognised as special syntax. Whitespace can be used between tokens and will
// be ignored.
std::queue<std::string> Tokenise(const std::string& filter) {
  std::queue<std::string> result;
  auto it = filter.begin();
  const auto end = filter.end();
  while (it != end) {
    if (std::isspace(*it)) {
      ++it;
    } else if (std::strchr(kTokenCharacters, *it)) {
      result.emplace(&*it, 1);
      ++it;
    } else if (std::isgraph(*it)) {
      auto name = it;
      ++it;
      while (it != end && std::isgraph(*it)
             && !std::strchr(kTokenCharacters, *it)) {
        ++it;
      }
      result.emplace(&*name, it - name);
    } else {
      Die() << "unexpected character in filter: '" << *it;
    }
  }

  return result;
}

// The failing parser.
std::unique_ptr<Filter> Fail(
    const std::string& message, std::queue<std::string>& tokens) {
  std::ostringstream os;
  os << "syntax error in filter expression: '" << message << "'; context:";
  for (size_t i = 0; i < 3; ++i) {
    os << ' ';
    if (tokens.empty()) {
      os << "<end>";
      break;
    }
    os << '"' << tokens.front() << '"';
    tokens.pop();
  }
  Die() << os.str();
}

std::unique_ptr<Filter> Expression(std::queue<std::string>& tokens);

// Parse a filter atom.
std::unique_ptr<Filter> Atom(std::queue<std::string>& tokens) {
  if (tokens.empty()) {
    return Fail("expected a filter expression", tokens);
  }
  auto token = tokens.front();
  tokens.pop();
  if (token == "(") {
    auto expression = Expression(tokens);
    if (tokens.empty() || tokens.front() != ")") {
      return Fail("expected a ')'", tokens);
    }
    tokens.pop();
    return expression;
  } else if (token == ":") {
    if (tokens.empty()) {
      return Fail("expected a file name", tokens);
    }
    token = tokens.front();
    tokens.pop();
    return std::make_unique<SetFilter>(ReadAbigail(token));
  } else {
    if (std::strchr(kTokenCharacters, token[0])) {
      return Fail("expected a glob token", tokens);
    }
    return std::make_unique<GlobFilter>(token);
  }
}

// Parse a filter factor.
std::unique_ptr<Filter> Factor(std::queue<std::string>& tokens) {
  bool invert = false;
  while (!tokens.empty() && tokens.front() == "!") {
    tokens.pop();
    invert = !invert;
  }
  auto atom = Atom(tokens);
  if (invert) {
    atom = std::make_unique<NotFilter>(std::move(atom));
  }
  return atom;
}

// Parse a filter term.
std::unique_ptr<Filter> Term(std::queue<std::string>& tokens) {
  auto factor = Factor(tokens);
  while (!tokens.empty() && tokens.front() == "&") {
    tokens.pop();
    factor = std::make_unique<AndFilter>(std::move(factor), Factor(tokens));
  }
  return factor;
}

// Parse a filter expression.
std::unique_ptr<Filter> Expression(std::queue<std::string>& tokens) {
  auto term = Term(tokens);
  while (!tokens.empty() && tokens.front() == "|") {
    tokens.pop();
    term = std::make_unique<OrFilter>(std::move(term), Term(tokens));
  }
  return term;
}

}  // namespace

// Tokenise and parse a filter expression.
std::unique_ptr<Filter> MakeFilter(const std::string& filter)
{
  auto tokens = Tokenise(filter);
  auto result = Expression(tokens);
  if (!tokens.empty()) {
    return Fail("unexpected junk at end of filter", tokens);
  }
  return result;
}

void FilterUsage(std::ostream& os) {
  os << "filter syntax:\n"
     << "  <filter>   ::= <term>          |  <expression> '|' <term>\n"
     << "  <term>     ::= <factor>        |  <term> '&' <factor>\n"
     << "  <factor>   ::= <atom>          |  '!' <factor>\n"
     << "  <atom>     ::= ':' <filename>  |  <glob>  |  '(' <expression> ')'\n"
     << "  <filename> ::= <string>\n"
     << "  <glob>     ::= <string>\n";
}

}  // namespace stg