xref: /aosp_15_r20/external/regex-re2/re2/testing/required_prefix_test.cc (revision ccdc9c3e24c519bfa4832a66aa2e83a52c19f295)
1 // Copyright 2009 The RE2 Authors.  All Rights Reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4 
5 #include <string>
6 
7 #include "util/test.h"
8 #include "util/logging.h"
9 #include "re2/regexp.h"
10 
11 namespace re2 {
12 
13 struct PrefixTest {
14   const char* regexp;
15   bool return_value;
16   const char* prefix;
17   bool foldcase;
18   const char* suffix;
19 };
20 
21 static PrefixTest tests[] = {
22   // If the regexp is missing a ^, there's no required prefix.
23   { "abc", false },
24   { "", false },
25   { "(?m)^", false },
26 
27   // If the regexp immediately goes into
28   // something not a literal match, there's no required prefix.
29   { "^(abc)", false },
30   { "^a*",  false },
31 
32   // Otherwise, it should work.
33   { "^abc$", true, "abc", false, "(?-m:$)" },
34   { "^abc", true, "abc", false, "" },
35   { "^(?i)abc", true, "abc", true, "" },
36   { "^abcd*", true, "abc", false, "d*" },
37   { "^[Aa][Bb]cd*", true, "ab", true, "cd*" },
38   { "^ab[Cc]d*", true, "ab", false, "[Cc]d*" },
39   { "^☺abc", true, "☺abc", false, "" },
40 };
41 
TEST(RequiredPrefix,SimpleTests)42 TEST(RequiredPrefix, SimpleTests) {
43   for (int i = 0; i < arraysize(tests); i++) {
44     const PrefixTest& t = tests[i];
45     for (int j = 0; j < 2; j++) {
46       Regexp::ParseFlags flags = Regexp::LikePerl;
47       if (j == 0)
48         flags = flags | Regexp::Latin1;
49       Regexp* re = Regexp::Parse(t.regexp, flags, NULL);
50       ASSERT_TRUE(re != NULL) << " " << t.regexp;
51 
52       string p;
53       bool f;
54       Regexp* s;
55       ASSERT_EQ(t.return_value, re->RequiredPrefix(&p, &f, &s))
56         << " " << t.regexp << " " << (j==0 ? "latin1" : "utf")
57         << " " << re->Dump();
58       if (t.return_value) {
59         ASSERT_EQ(p, string(t.prefix))
60           << " " << t.regexp << " " << (j==0 ? "latin1" : "utf");
61         ASSERT_EQ(f, t.foldcase)
62           << " " << t.regexp << " " << (j==0 ? "latin1" : "utf");
63         ASSERT_EQ(s->ToString(), string(t.suffix))
64           << " " << t.regexp << " " << (j==0 ? "latin1" : "utf");
65         s->Decref();
66       }
67       re->Decref();
68     }
69   }
70 }
71 
72 }  // namespace re2
73