• 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 extern const char kFilePattern_Help[];
16 
17 class Pattern {
18  public:
19   struct Subrange {
20     enum Type {
21       LITERAL,       // Matches exactly the contents of the string.
22       ANYTHING,      // * (zero or more chars).
23       PATH_BOUNDARY  // '/' or beginning of string.
24     };
25 
26     explicit Subrange(Type t, const std::string& l = std::string())
typeSubrange27         : type(t), literal(l) {}
28 
29     // Returns the minimum number of chars that this subrange requires.
MinSizeSubrange30     size_t MinSize() const {
31       switch (type) {
32         case LITERAL:
33           return literal.size();
34         case ANYTHING:
35           return 0;
36         case PATH_BOUNDARY:
37           return 0;  // Can match beginning or end of string, which is 0 len.
38         default:
39           return 0;
40       }
41     }
42 
43     Type type;
44 
45     // When type == LITERAL this is the text to match.
46     std::string literal;
47   };
48 
49   explicit Pattern(const std::string& s);
50   Pattern(const Pattern& other);
51   ~Pattern();
52 
53   // Returns true if the current pattern matches the given string.
54   bool MatchesString(const std::string& s) const;
55 
56  private:
57   // allow_implicit_path_boundary determines if a path boundary should accept
58   // matches at the beginning or end of the string.
59   bool RecursiveMatch(const std::string& s,
60                       size_t begin_char,
61                       size_t subrange_index,
62                       bool allow_implicit_path_boundary) const;
63 
64   std::vector<Subrange> subranges_;
65 
66   // Set to true when the subranges are "*foo" ("ANYTHING" followed by a
67   // literal). This covers most patterns so we optimize for this.
68   bool is_suffix_;
69 };
70 
71 class PatternList {
72  public:
73   PatternList();
74   PatternList(const PatternList& other);
75   ~PatternList();
76 
is_empty()77   bool is_empty() const { return patterns_.empty(); }
78 
79   void Append(const Pattern& pattern);
80 
81   // Initializes the pattern list from a give list of pattern strings. Sets
82   // |*err| on failure.
83   void SetFromValue(const Value& v, Err* err);
84 
85   bool MatchesString(const std::string& s) const;
86   bool MatchesValue(const Value& v) const;
87 
88  private:
89   std::vector<Pattern> patterns_;
90 };
91 
92 #endif  // TOOLS_GN_PATTERN_H_
93