• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef TOOLS_GN_PATTERN_H_
6 #define TOOLS_GN_PATTERN_H_
7 
8 #include <stddef.h>
9 
10 #include <string>
11 #include <vector>
12 
13 #include "gn/value.h"
14 
15 class Pattern {
16  public:
17   struct Subrange {
18     enum Type {
19       LITERAL,       // Matches exactly the contents of the string.
20       ANYTHING,      // * (zero or more chars).
21       PATH_BOUNDARY  // '/' or beginning of string.
22     };
23 
24     explicit Subrange(Type t, const std::string& l = std::string())
typeSubrange25         : type(t), literal(l) {}
26 
27     // Returns the minimum number of chars that this subrange requires.
MinSizeSubrange28     size_t MinSize() const {
29       switch (type) {
30         case LITERAL:
31           return literal.size();
32         case ANYTHING:
33           return 0;
34         case PATH_BOUNDARY:
35           return 0;  // Can match beginning or end of string, which is 0 len.
36         default:
37           return 0;
38       }
39     }
40 
41     Type type;
42 
43     // When type == LITERAL this is the text to match.
44     std::string literal;
45   };
46 
47   explicit Pattern(const std::string& s);
48   Pattern(const Pattern& other);
49   ~Pattern();
50 
51   // Returns true if the current pattern matches the given string.
52   bool MatchesString(const std::string& s) const;
53 
54  private:
55   // allow_implicit_path_boundary determines if a path boundary should accept
56   // matches at the beginning or end of the string.
57   bool RecursiveMatch(const std::string& s,
58                       size_t begin_char,
59                       size_t subrange_index,
60                       bool allow_implicit_path_boundary) const;
61 
62   std::vector<Subrange> subranges_;
63 
64   // Set to true when the subranges are "*foo" ("ANYTHING" followed by a
65   // literal). This covers most patterns so we optimize for this.
66   bool is_suffix_;
67 };
68 
69 class PatternList {
70  public:
71   PatternList();
72   PatternList(const PatternList& other);
73   ~PatternList();
74 
is_empty()75   bool is_empty() const { return patterns_.empty(); }
76 
77   void Append(const Pattern& pattern);
78 
79   // Initializes the pattern list from a give list of pattern strings. Sets
80   // |*err| on failure.
81   void SetFromValue(const Value& v, Err* err);
82 
83   bool MatchesString(const std::string& s) const;
84   bool MatchesValue(const Value& v) const;
85 
86  private:
87   std::vector<Pattern> patterns_;
88 };
89 
90 #endif  // TOOLS_GN_PATTERN_H_
91